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 module
export const myFunction = () => {
/* ... */
};
export default myFunction;
// Importing a module
import { 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.js
export 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.js
const 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.js
import { myFunction, myVariable } from './myModule';
myFunction(); // This is my function
console.log(myVariable); // 42
Importing default exports
To import a default export, use the import
statement followed by a name of your choice.
// main.js
import 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.js
import * as myModule from './myModule';
myModule.myFunction(); // This is my function
console.log(myModule.myVariable); // 42