Modules in JavaScript¶
A JavaScript module is a self-contained unit of code that encapsulates related functionality. They help to modularize your codebase, making it easier to manage and reuse code across different parts of your application. Modules can expose certain features or variables to be used by other modules while keeping the rest of their implementation private1.
Creating a Module¶
A module in JavaScript is just a file of code2. You can think of a module as a reusable and independent unit of code2. As your application gets bigger, you can split your code up into multiple files, aka modules2.
// myModule.js
export function myFunction() {
return 'Hello, World!';
}
In this example, myFunction is exported from the module, which means it can be imported into other modules.
Importing a Module¶
Modules are imported from external files with the import statement3.
// app.js
import { myFunction } from './myModule.js';
console.log(myFunction()); // Outputs: 'Hello, World!'
In this example, myFunction is imported from myModule.js and then used in app.js.
Default Exports¶
Each module can have one default export4. Default exports are especially easy to import4.
// myModule.js
export default function myFunction() {
return 'Hello, World!';
}
// app.js
import myFunction from './myModule.js';
console.log(myFunction()); // Outputs: 'Hello, World!'
In this example, myFunction is the default export of myModule.js, so it can be imported without using curly braces.
Named Exports¶
A module can have multiple named exports4. You can import a specific named export using curly braces4.
// myModule.js
export function function1() {
return 'Hello, World!';
}
export function function2() {
return 'Goodbye, World!';
}
// app.js
import { function1, function2 } from './myModule.js';
console.log(function1()); // Outputs: 'Hello, World!'
console.log(function2()); // Outputs: 'Goodbye, World!'
In this example, function1 and function2 are named exports of myModule.js, so they can be imported individually.
Browser Compatibility¶
Modern browsers have started to support module functionality natively4. Use of native JavaScript modules is dependent on the import and export statements4. These are supported in browsers as shown in the compatibility table4.