JavaScript Modules
Learn how to organize your code with JavaScript modules.
1. Exporting from a Module
You can export features out of a module using the export
statement. This makes them available for other modules to import.
JavaScript Code
Live JavaScript representation with highlighted changes
// modules/math.jsexport const PI = 3.14159;export function add(a, b) {return a + b;}
2. Importing into a Module
You can import features into a module using the import
statement. You need to specify the path to the module.
JavaScript Code
Live JavaScript representation with highlighted changes
// main.jsimport { PI, add } from './modules/math.js';console.log(PI);console.log(add(2, 3));
3. Default Exports
A module can have one default export. This is useful for modules that export only one main thing.
JavaScript Code
Live JavaScript representation with highlighted changes
// modules/my-module.jsexport default function myFunction() {console.log("Hello from my module!");}
JavaScript Code
Live JavaScript representation with highlighted changes
// main.jsimport myFunc from './modules/my-module.js';myFunc();