ES6 Modules
Table of contents
ES6 Modules
Everything inside an ES6 module is private by default, and runs in strict mode (there’s no need for 'use strict'
). Public variables, functions and classes are exposed using export.
For example:
js
// lib.jsexport const PI = 3.1415926;export function sum(...args) {log('sum', args);return args.reduce((num, tot) => tot + num);}export function mult(...args) {log('mult', args);return args.reduce((num, tot) => tot * num);}// private functionfunction log(...msg) {console.log(...msg);}
Alternatively, a single export statement can be used. For example:
js
// lib.jsconst PI = 3.1415926;function sum(...args) {log('sum', args);return args.reduce((num, tot) => tot + num);}function mult(...args) {log('mult', args);return args.reduce((num, tot) => tot * num);}// private functionfunction log(...msg) {console.log(...msg);}export { PI, sum, mult };
import
is then used to pull items from a module into another script or module:
js
// main.jsimport { sum } from './lib.js';console.log( sum(1, 2, 3, 4) ); // 10
In this case, lib.js is in the same folder as main.js.
Multiple items can be imported at one time:
js
import { sum, mult } from './lib.js';console.log( sum(1,2,3,4) ); // 10console.log( mult(1,2,3,4) ); // 24
and imports can be aliased to resolve naming collisions:
js
import { sum as addAll, mult as multiplyAll } from './lib.js';console.log( addAll(1,2,3,4) ); // 10console.log( multiplyAll(1,2,3,4) ); // 24
Finally, all public items can be imported by providing a namespace:
js
import * as lib from './lib.js';console.log( lib.PI ); // 3.1415926console.log( lib.add(1,2,3,4) ); // 10console.log( lib.mult(1,2,3,4) ); // 24
Using ES6 Modules in Browsers
Scripts which use modules must be loaded by setting a type="module"
attribute in the <script>
tag.
js
<script type="module" src="./main.js"></script>
or inline:
js
<script type="module">import { something } from './somewhere.js';// ...</script>