How do you import and export modules in JavaScript?
TL;DR
In JavaScript, you can import and export modules using the import
and export
statements. To export a module, you can use export
before a function, variable, or class, or use export default
for a single default export. To import a module, you use the import
statement followed by the name of the exported module and the path to the module file.
// Exporting a moduleexport const myFunction = () => {/* ... */};export default myFunction;// Importing a moduleimport { myFunction } from './myModule';import myFunction from './myModule';
Exporting modules
Named exports
You can export multiple named items from a module. Use the export
keyword before the function, variable, or class you want to export.
// myModule.jsexport const myFunction = () => {console.log('This is my function');};export const myVariable = 42;
Default exports
A module can have one default export. Use the export default
keyword to export a single item.
// myModule.jsconst myFunction = () => {console.log('This is my function');};export default myFunction;
Importing modules
Importing named exports
To import named exports, use the import
statement followed by curly braces containing the names of the exports.
// main.jsimport { myFunction, myVariable } from './myModule';myFunction(); // This is my functionconsole.log(myVariable); // 42
Importing default exports
To import a default export, use the import
statement followed by a name of your choice.
// main.jsimport myFunction from './myModule';myFunction(); // This is my function
Importing all exports
You can import all named exports from a module using the *
syntax and an alias.
// main.jsimport * as myModule from './myModule';myModule.myFunction(); // This is my functionconsole.log(myModule.myVariable); // 42