Hello fellow JavaScript developers!
I’m looking for some guidance on structuring my code. Is there a way to JavaScript include file, like how we use @import
in CSS, to load one .js
file within another?
I’m trying to keep my code modular and organized, but I’m not entirely sure of the best, most modern method to link files together effectively when running scripts directly in a browser.
Any advice on the best practices or methods for this would be greatly appreciated! Thanks in advance for the help! 
Hey @sakshikuchroo , the most modern and clean way to include one JS file inside another is by using ES6 modules. You can export what you need from one file and import it in another.
For example:
// utils.js
export function greet(name) {
return `Hello, ${name}!`;
}
// main.js
import { greet } from './utils.js';
console.log(greet('sakshikuchroo'));
Just make sure to include your script tag in HTML with type="module"
like this:
<script type="module" src="main.js"></script>
This tells the browser to treat the files as modules, allowing you to use import
and export
seamlessly. It keeps your code modular and easier to maintain!
if you’re running scripts directly in the browser and want to load another JavaScript file dynamically, you can create a script element and append it to the document.
Here’s how:
function loadScript(url, callback) {
const script = document.createElement('script');
script.src = url;
script.onload = () => callback && callback();
document.head.appendChild(script);
}
// Usage:
loadScript('utils.js', () => {
console.log('utils.js loaded!');
// You can now use functions or variables from utils.js here
});
This method doesn’t require ES modules and works in all browsers. It’s handy if you want to load scripts conditionally or after some event.
Hey @sakshikuchroo, if you’re working in a Node.js environment or using bundlers like Webpack or Rollup, you can use CommonJS require()
syntax to include files:
// utils.js
function greet(name) {
return `Hello, ${name}!`;
}
module.exports = greet;
// main.js
const greet = require('./utils.js');
console.log(greet('sakshikuchroo'));
This won’t work natively in browsers but is very common in backend Node.js code or frontend projects that use build tools to bundle modules before deployment.
So if you’re planning to scale or use tooling, this is a solid approach.