I’m working on a JavaScript project and I need to use functions from one JS file in another file. In CSS we have the @import rule to bring in external stylesheets. Is there something similar for JavaScript files?
I have a file called utilities.js with some helper functions:
function calculateTotal(price, tax) {
return price + (price * tax);
}
function formatCurrency(amount) {
return '$' + amount.toFixed(2);
}
And I want to use these functions in my main app.js file:
let itemPrice = 100;
let taxRate = 0.08;
let total = calculateTotal(itemPrice, taxRate);
let displayPrice = formatCurrency(total);
console.log('Final price: ' + displayPrice);
What’s the proper way to make the functions from utilities.js available in app.js? I’ve seen different approaches but I’m not sure which one is the standard method.
you can also use script tags in HTML if ur not using modules. Just add <script src="utilities.js"></script> before your app.js script tag and the functions will be globally available. It’s old school but works fine for smaller projects w/o build tools.
To import functions from one JS file to another, ES6 modules are generally the preferred method for both browser and Node.js environments. In your utilities.js file, prefix your function declarations with export or use export { calculateTotal, formatCurrency } at the end of the file. In app.js, you would then use import { calculateTotal, formatCurrency } from './utilities.js'. Ensure that your HTML script tag includes type="module" for this to work in the browser. If you’re working in Node.js, you can utilize CommonJS syntax with module.exports and require(), but ES6 offers better advantages with modern tooling.
You could also try dynamic imports with import() - they’re great for conditional loading or async module loading. This returns a promise and lets you import modules at runtime instead of at the top of your file. In your case, you’d write import('./utilities.js').then(module => { const total = module.calculateTotal(itemPrice, taxRate); }) inside app.js. Just remember your functions need to be exported from utilities.js first. Dynamic imports are really useful for bigger modules you don’t always need right away - helps with performance too.