0

I have a wordpress site that loads a single app.js file filled with jQuery that handles functionality for the entire site. It is incredibly long and difficult to navigate. I would like to switch over to something like a SCSS partials approach, where I can create separate files for reusable code or single pages, and then load those files into one single app.js file.

I know that jQuery has a $.getScript() function, but my understanding is that I cannot use this while developing on my localhost, and that trying to load files stored locally will not work because of the nature of the $.getScript() AJAX request.

Are there other options that would allow me to create smaller snippets of js, and then import them into a single parent file? I would prefer not to load 25 separate scripts in my <head> for each reusable bit of js I write.

|--js
|  |-- app.js
|  |-- partials
|  |  |-- partialOne.js
|  |  |-- partialTwo.js
1

1 Answer 1

1

One option would be to export data from your "partial" .js files into modules and import into the app.js.

as a simple example, suppose your partialOne.js has functions to sum and multiple values:

let sum = (a,b) => {
    return a+b;
}

let multiply = (a,b) => {
    return a*b;
}

export {sum, multiply};

Here I'm using functions, but you can export anything, from arrays, objects, variables, etc. Now, in your app.js, you must import them:

import {sum, multiply} from "./file_path/partialOne.js"

console.log(sum(2,3));
console.log(multiply(5,5));

For more info on using modules, check https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.