Skip to content

Instantly share code, notes, and snippets.

@AndrewGibson27
Last active November 30, 2017 20:10
Show Gist options
  • Save AndrewGibson27/55628dc85b1fcecb8f6380376290d5e2 to your computer and use it in GitHub Desktop.
Save AndrewGibson27/55628dc85b1fcecb8f6380376290d5e2 to your computer and use it in GitHub Desktop.

ES6 Modules

You can destructure when the export is an object.

// file1.js
export { foo, bar };

// index.js
import { foo } from './file1';

You cannot destructure when the export is an object, and the export is the default:

// file1.js
export default { foo, bar };

// index.js
import { foo } from './file1'; // does not work

ES6 combined with CommonJS

When compiling a library written in ES6 into CommonJS (with Webpack or Rollup), and that library will eventually be imported into an ES6 module, you can use either export or export default.

// library.js
export default { modOne, modTwo }; // will be compiled to CJS

// otherLibrary.js
export { modOne, modTwo }; // will be compiled to CJS

// myfile.js
import { modOne } from 'library.js'; // works
import { modOne } from 'otherLibrary.js'; // works

When importing an ES6 library into a CommonJS module, the ES6 library should always use export instead of export default. That's so you can avoid having to reference the default key.

// library.js
export default { modOne, modTwo };

// otherLibrary.js
export { modOne, modTwo };

// myfile.js
import { modOne } from 'library.js'; // does not work
import { modOne } from 'otherLibrary.js'; // works

import library from 'library.js';
const { modOne } = library.default; // works

When a CommonJS module's exports is set to a single function or value, you must reference it in an ES6 module as if it's the default.

// library.js
function fooBar() {
  console.log('hey');
}

module.exports = fooBar;

// myfile.js
import fooBar from 'library.js'; // works
import { fooBar } from 'library.js'; // does not work

When compiling a library written in ES6 to CommonJS, do not use export default in addition to export. Consumers of the library will have to reference it using the default key.

// library.js
export default function modOne() { // will be compiled to CJS
  console.log('hey');
}

export function modTwo() { // will be compiled to CJS
  console.log('ho');
}

// myfile.js
const lib = require('./dist/bundle');

const { modTwo } = lib;

lib.default();
modTwo();

When compiling a library written in ES6 to CommonJS, and the library has a single export default, you can reference it in CommonJS without curly braces.

// library.js
export default function modOne() { // will be compiled to CJS
  console.log('hey');
}

// myfile.js
const lib = require('./dist/bundle');

lib();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment