JavaScript's built-in module system
Well, both AMD and CommonJS are community standards and not a part of the language specification. However, with EcmaScript 6th edition, JavaScript acquired its own module system. At the moment, no browser yet supports this feature, so we have to install the Babel.js transpiler to fiddle with the examples.
Since we already have Node.js that is distributed with NPM (the Node.js package manager), we now can run the following command:
npm install babel -g
Named exports
Now we can write a module as follows:
foo.es6
export let bar = "bar"; export let baz = "baz";
In ES6, we can export multiple elements. Any declaration prefixed with the keyword export becomes available for import:
main.es6
import { bar, baz } from "./foo"; console.log( bar ); // bar console.log( baz ); // baz
Since we don't yet have any support for ES6 modules in the browser, we will transpile them into CommonJS or AMD. Here Babel.js helps us:
babel --modules...