EN
JavaScript - export statement
0 points
In this article, we would like to show you how to use the export statement in JavaScript.
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.
Named exports:
xxxxxxxxxx
1
// export features declared earlier
2
export { myFunction, myVariable };
3
4
// export individual features such as variables, constants, functions, classes
5
export let myVariable = 3;
6
export function myFunction() { /* ... */ };
Default exports:
xxxxxxxxxx
1
// export feature declared earlier
2
export { myFunction as default };
3
4
// export individual features
5
export default function () { /* ... */ }
6
export default class { /* ... */ }
Note:
Each subsequent export overwrites the previous one.
module.js file:
xxxxxxxxxx
1
function myFunction() {
2
console.log('My function text');
3
}
4
5
const myConstant = 1;
6
7
var myObject = {
8
id: 1,
9
color: 'red',
10
};
11
12
export { myFunction, myConstant, myObject };
index.js file:
xxxxxxxxxx
1
import { myFunction, myConstant, myObject } from './module.js';
2
3
myFunction(); // My function text
4
console.log(myConstant); // 1
5
console.log(myObject.color); // red
Output after running index.js under Node.js:
xxxxxxxxxx
1
My function text
2
1
3
red
module.js file:
xxxxxxxxxx
1
export default function myFunction() {
2
console.log('My function text');
3
}
index.js file:
xxxxxxxxxx
1
import myFunction from './module.js';
2
3
myFunction(); // My function text
Output after running index.js under Node.js:
xxxxxxxxxx
1
My function text