ES6 modules
ES6 is the first time JavaScript has built in modules.
The goal of ES6 modules was to create a format that both users of CommonJS and of AMD are happy with. Its syntax is even more compact than CommonJS. Their structure can be statically analyzed. Their support of cyclic dependencies is better than CommonJS. Similar to AMD, they have direct support for asynchronous loading and configurable module loading.
Use of native JavaScript modules is dependent on the import
and export
statements.
// file name "sum.js"
function sum(a, b) {
return a+b;
}
export { sum };
// file name "main.js"
import { sum } from "./sum.js";
let result = sum(1,2);
console.log(result); //3
<script type="module" src="main.js"></script>
To get modules to work correctly in a browser, you need to make sure that your server is serving them with a Content-Type
header that contains a JavaScript
MIME type such as text/javascript
Named Export
With named exports, one can have multiple named exports per file. The name of the imported module has to be the same as the name of the exported module.
// File lib.js
function foo() {
console.log('foo');
}
function baz() {
console.log('baz');
}
export {foo, baz};
// File app.js
import {foo, baz} from './lib.js';
foo();
baz();
Default Export
There can only be one default export per file. The naming of import is completely independent in default export and we can use any name we like.
// File lib.js
function foo() {
console.log('foo');
}
export default foo;
// File app.js
import XYZ from './foo.js';
XYZ(); // prints 'foo'
We can have both named exports and default export in the same module.
// File lib.js
export default function foo() {
console.log('foo');
}
export function baz() {
console.log('baz');
}
// File app.js
import foo, {baz} from './lib.js';
foo();
baz();
Renaming imports
If 2 modules import names collide we would need to rename when importing.
//File foo-a.js
export function foo() {
console.log('foo a');
}
//File foo-b.js
export function foo() {
console.log('foo b');
}
//File app.js
import {foo as fooA} from 'foo-a.js';
import {foo as fooB} from 'foo-b.js';
fooA(); //prints 'foo a'
fooB(); //prints 'foo b'
Renaming exports
Renaming exports are similar to renaming exports. If you want to export the same value under different names.
function foo() {
console.log('foo');
}
export {
foo as fooV1,
foo as fooV2
};