What's the best way to import one JS file into another JS file?

I’m currently engaged in a project where I need to access functions from one JavaScript file in another. Just like using @import in CSS to bring in styles, is there a comparable method for JavaScript?

I’ve been exploring how to establish proper links between my files. For instance, I have a file named utilities.js that contains some helper functions:

function calculateTotal(price, tax) {
    return price + (price * tax);
}

function formatCurrency(amount) {
    return '$' + amount.toFixed(2);
}

Now, I aim to use these functions in my main file, app.js. What is the best way to accomplish this? I’ve come across various methods, but I’m uncertain about which one to choose and how to execute it correctly.

honestly, just go with es6 modules - way cleaner than the old methods. in utilities.js, add export before each function. then in app.js: import { calculateTotal, formatCurrency } from './utilities.js'. don’t forget type="module" in your html script tag or it won’t work.

The approach you take depends on your environment. For modern browsers and Node.js, the ES6 module system is ideal. You would export your functions from utilities.js using the export keyword and then import them into app.js with the import statement. If you are dealing with older browsers and not using any build tools, you might resort to using script tags, but this creates a global scope which can complicate things in larger applications. Alternatively, in a Node.js environment, you can also utilize CommonJS by using module.exports in utilities.js and require in app.js. Generally, I suggest starting with ES6 modules given their clarity and alignment with modern coding practices, even if there’s a slight overhead in setup.

If you’re working in a regular browser without build tools, the script tag approach works great. Just include your utilities.js before your main app.js file in your HTML. To keep things clean, modify your utilities.js to attach functions to a namespace object instead of dumping everything into the global scope. Create a utilities object and assign your functions to it. I’ve used this method tons of times on smaller projects where setting up module bundlers is total overkill. But if you’re planning to scale your app, learn ES6 modules now - you’ll thank yourself later.