Note: This blog post, like most of mine, is a work in progress. If you see somethinig that does seem quite right, let me know @dicshaunary.
If you read nothing else, read this: http://2ality.com/2014/09/es6-modules-final.html and then perhaps this: https://addyosmani.com/writing-modular-js/ too. The following are my own notes.
ECMAScript 2015 (ECMA6) Module System
Two primary types of ECMA6 exports:
- named exports
- default exports - a named export that happens to be named
default
.
// listed named export
export { name1, name2, …, nameN };
// listed named export with renames
export { variable1 as name1, variable2 as name2, …, nameN };
// named export of declaration
export let name1, name2, …, nameN; // also var
export let name1 = …, name2 = …, …, nameN; // also var, const
// default export of an expression
export default expression;
export default function (…) { … } // also class, function*
export default function name1(…) { … } // also class, function*
// default export
export { name1 as default, … };
// re-export
export * from …;
// selective re-export
export { name1, name2, …, nameN } from …;
// selective re-export with rename
export { import1 as name1, import2 as name2, …, nameN } from …;
// default import
import defaultMember from "module-name";
// importing the module as an object
import * as name from "module-name";
// named import
import { member } from "module-name";
// named import with a rename
import { member as alias } from "module-name";
// multiple named import
import { member1 , member2 } from "module-name";
// multiple named import with one a rename
import { member1 , member2 as alias2 , [...] } from "module-name";
// default and named import
import defaultMember, { member [ , [...] ] } from "module-name";
// importing the default and the module as an object
import defaultMember, * as name from "module-name";
// load the module without importing anything
import "module-name";
Legacy JavaScript Module Systems
AMD (RequireJS) Module System
- https://github.com/amdjs/amdjs-api/wiki/AMD
- Uses
define
in the system. - RequireJS is an implementation of AMD.
CommonJS (NodeJS) Module System
- https://nodejs.org/api/modules.html
- http://www.commonjs.org/specs/modules/1.0/
- NodeJS is an implementation of CommonJS with a few additional features.
module.exports =
exports =
module.require(id)
require(id)
Some Practical Notes
TypeScript compiles export default { }
to exports.default = { }
. In legacy code, we can load that via require('id').default
and in modern code with import someName from 'id'
.