Modules Learn how to import and export JS code as a module or package.

A module is just a file that exports some JavaScript code.

First, a file exports (package) something useful…

file_type_js_official awesome-pacakge.js
export default '๐Ÿง';

Second, a different file uses this code by importing it.

file_type_js_official my-app.js
import cupcake from '../path/to/awesome-package.js';

Pretty simple! But there more you should know.

Default Exports

A module can specify at most 1 default export.

export default '๐Ÿง';

This allows the consumer to name the module whatever it prefers when importing.

// wait, that's not pizza...
import pizza from '../path/to/awesome-package';

This is ideal for modules that export a single class or function.

Named Exports

Some modules might offer a collection of independent helper functions, like RxJS or Lodash. A better option for such packages is named exports.

export const cupcake = '๐Ÿง';
export const pizza = '๐Ÿ•';

If the consumer only wants pizza, they can import it by name - this is called treeshaking or dead code elimination.

import { pizza } from '../path/to/awesome-package'; 

How to change the name of an import?

If you don’t like the exported name, you can change it with the as keyword.

import { pizza as awesomePizza } from '../path/to/awesome-package'; 

console.log(awesomePizza);

How to export a list of variables?

A module may have many variables to export and this can get messy. Use an export list to make your code more succinct and organized.

const cupcake = '๐Ÿง';
const pizza = '๐Ÿ•';

export { 
    cupcake,
    pizza
}

Additional Resources

Questions?

Ask questions via GitHub below OR chat on Slack #questions