JavaScript Module system allows you to export a single variable or multiple variables using named export. There are two ways of using named export:
1. Export individual variables by writing export at the beginning of their declaration.
export let msg = 'Hello, World!'; export let arr = [10, 20, 30, 40];
2. Export variables after they have been declared by exporting them as an object.
let msg = 'Hello, World!'; let arr = [10, 20, 30, 40]; export {msg, arr};
After exporting them, you can import the variables using the import keyword.
import {msg, arr} from './app.js' console.log(msg); //'Hello, World!' console.log(arr); //[10, 20, 30, 40]
There is another way of exporting variables which is default export. Using default export, you can export only a single variable. If you try to use multiple export defaults in a file, you will get an error.
export default let msg = 'Hello, World!'; //The below line will give error. export default let arr = [10, 20, 30, 40];
Let's import the variable exported as default.
import msg from './app.js'; console.log(msg); //'Hello, World!'
You can also use named and default exports in a single file.
let msg = 'Hello, World!'; export let arr = [10, 20, 30, 40]; export default msg;
Here, is how you would use import default and named imports simultaneously.
import msg, {arr} from './app.js'; console.log(msg); //'Hello, World!' console.log(arr); //[10, 20, 30, 40]