Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A summary of Jason Orendorff’s Mozilla Hacks post on ES6 modules

ECMAScript Modules

  • modules are automatically strict mode
  • declarations inside a module are scoped to that module (not visible by other scripts)
  • ECMAScript does not define what import does (it’s left up to the implementation)
  • there is no error recovery; “if anything fails to load or link, nothing runs”
  • exporting:
    • you can export any top-level function, class, var, let, or const

      export function fn() { ... };
    • you can export lists, which can appear anywhere in a module’s top-level scope and can be combined with other export declarations

      export {a, b as bravo};
    • you can designate one of the exports as the default export

      export default function fn() { ... }; 
      
      // or in a list:
      export {a, b as bravo, fn as default};
    • you can re-export from other modules (similar to import-from followed by export, except that re-exported bindings won’t be added to the current module’s scope)

      export {c, d} from 'other';
      export * from 'other'; // re-export everything
  • importing:
    • you can import named exports (and optionally rename them)

      import {a, bravo, c as charlie} from 'module';
    • you can import the default export of a module (incl. CommonJS or AMD modules) by ommiting the braces

      // same value as require('lodash') in CommonJS
      import _ from 'lodash';
    • you can import both the default export and named exports at the same time

      import _, {each, map} from 'lodash';
      // or
      import {default as _, each, map} from 'lodash';
    • you can import a module’s namespace object, which contains all the module’s exports as properties

      import * as user from 'user'; 

Read the full blog post here.

@simevidas

This comment has been minimized.

Copy link
Owner Author

@simevidas simevidas commented Dec 1, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.