EN
JavaScript - export statement
0
points
In this article, we would like to show you how to use the export statement in JavaScript.
Description
The export
statement is used when creating modules that can be used by other programs with the import
statement. There are two different types of export, named and default. You can have multiple named exports per module but only one default export.
Syntax
Named exports:
// export features declared earlier
export { myFunction, myVariable };
// export individual features such as variables, constants, functions, classes
export let myVariable = 3;
export function myFunction() { /* ... */ };
Default exports:
// export feature declared earlier
export { myFunction as default };
// export individual features
export default function () { /* ... */ }
export default class { /* ... */ }
Note:
Each subsequent export overwrites the previous one.
Practical examples
Example 1 - using named exports
module.js file:
function myFunction() {
console.log('My function text');
}
const myConstant = 1;
var myObject = {
id: 1,
color: 'red',
};
export { myFunction, myConstant, myObject };
index.js file:
import { myFunction, myConstant, myObject } from './module.js';
myFunction(); // My function text
console.log(myConstant); // 1
console.log(myObject.color); // red
Output after running index.js under Node.js:
My function text
1
red
Example 2 - using default exports
module.js file:
export default function myFunction() {
console.log('My function text');
}
index.js file:
import myFunction from './module.js';
myFunction(); // My function text
Output after running index.js under Node.js:
My function text