[es6] import, export, default cheatsheet

Written by peterchang_82818 | Published 2017/06/19
Tech Story Tags: javascript | import | export | nodejs

TLDRvia the TL;DR App

There are 4 types of exports:

1— Named exports (several per module) 2**— Default exports** (one per module)3 — Mixed named & default exports 4**— Cyclical Dependencies**

1. Name exports

//------ lib.js ------export const sqrt = Math.sqrt;export function square(x) {    return x * x;}export function diag(x, y) {    return sqrt(square(x) + square(y));}//------ main.js ------import { square, diag } from 'lib';console.log(square(11)); // 121console.log(diag(4, 3)); // 5

or

//------ main.js ------import * as lib from 'lib';console.log(lib.square(11)); // 121console.log(lib.diag(4, 3)); // 5

2. Default exports (one per module)

//------ myFunc.js ------export default function () { ... };//------ main1.js ------import myFunc from 'myFunc';myFunc();

3. Mixed named & default exports

//------ underscore.js ------export default function (obj) {    ...};export function each(obj, iterator, context) {    ...}export { each as forEach };//------ main.js ------import _, { each } from 'underscore';...

4. Cyclical Dependencies

// lib.jsimport Main from 'main';var lib = {message: "This Is A Lib"};export { lib as Lib };

// main.jsimport { Lib } from 'lib';export default class Main {// ....}

Reference

http://2ality.com/2014/09/es6-modules-final.html


Published by HackerNoon on 2017/06/19