Skip to content

Instantly share code, notes, and snippets.

@michelle
Last active December 26, 2016 04:13
Show Gist options
  • Save michelle/42901268737b2c0c57d5b4f511ee4176 to your computer and use it in GitHub Desktop.
Save michelle/42901268737b2c0c57d5b4f511ee4176 to your computer and use it in GitHub Desktop.
ES6 imports & exports

This is a default export:

// in anything.js
const anything = 'You can export anything!';
export default anything;

This is the same as:

// in anything.js
export default 'You can export anything!';

If you're familiar with module.exports, this is the ES6 equivalent of doing module.exports = 'You can export anything!';

This is a default import:

import anything from './anything';

This is the same as:

import foobar from './anything';

Both of these are just saying, "import the default export of anything.js, and assign it to the variable anything (or, in the second case foobar)."

console.log(anything);
// prints "You can export anything!"

console.log(foobar);
// prints "You can export anything!"

These are named exports:

// in things.js
export const thing1 = 'one fish';
export const thing2 = 'two fish';
export const thing3 = 'red fish';
export const thing4 = 'blue fish';

This is the same as:

// in things.js
const thing1 = 'one fish';
const thing2 = 'two fish';
const thing3 = 'red fish';
const thing4 = 'blue fish';

export {thing1, thing2, thing3, thing4};

This is a named import:

import {thing1, thing3} from './things';

console.log(thing1, thing3)
// "one fish red fish"

These will not work:

// BAD
import thing2 from './things';
import {thing5} from './things';

console.log(thing2, thing5);
// will print "undefined undefined" because there is no default export or an export named `thing5` in things.js

You can rename imports:

import {thing1 as myThing1} from './things';

console.log(myThing1);
// prints "one fish"

You can combine default / named exports and imports. Under the hood, a default export is just a named export with the name default.

These are the same:

import defaultExport, {named1, named2, named3} from './exports';
import {default as defaultExport, named1, named2, named3} from './exports';

You can import all named exports:

import * as Things from './things';

console.log(Things);
// {thing1: 'one fish', thing2: 'two fish', thing3: 'red fish', thing4: 'blue fish'}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment