This document attempts to exhaustively explore the syntax of the ES6 Modules proposal.
Module syntax is valid only in module code. Script code is not
module code, so existing script tags cannot contain module code. The
intention is that HTML will add a module
tag and a default module
loader that is used to fetch and instantiate module code. See
dherman/web-modules for more
info on progress specifying the behavior of these components.
Modules export bindings. A module can export any number of named bindings and one default binding. Exported bindings are mutable - any changes to the value of the binding inside the module are reflected on the import side as well.
The following are the various ways to export bindings:
Named exports
// Export VariableStatement or Declaration
export var foo = { }; //
export function foo () { };
export function* foo () { };
export class foo () { };
export let foo = { };
// Export references
let x = 1, y = 2;
export { x, y as b };
Default export
// Export any AssignmentExpression
export default function foo() { };
export default class Bar { };
// Note: as above are expressions, these do not create local bindings.
// There is a proposal to make these declaration forms on ES-Discuss.
export default function() { };
export default { x: 1 };
Re-exporting bindings from another module
// Re-export all bindings from 'foo.js'
export * from 'foo.js';
// Note: open question how export * handles the default export of foo.js
// Re-export specific named bindings from foo.js
export {foo, bar} from 'foo.js';
// Re-export and re-name specific bindings from foo.js
export {foo as foo2} from 'foo.js';
Re-exporting the default export of another module is likely not going to be possible via export *
and export foo from "foo.js"
is a syntax error.
// Load foo.js, but don't create any bindings from it.
import "foo.js";
// Create all named exports of foo.js as properties on an object 'foo'
module foo from "foo.js";
// bind the default export of foo.js to 'foo';
import foo from "foo.js";
// bind named exports bar and baz from "foo.js"
import { bar, baz } from "foo.js";
// bind named exports with custom name
import { bar as bar2 } from "foo.js";
// bind both default and named exports from "foo.js"
import foo, { bar as bar2, baz } from "foo.js";