ES6 Modules

More than you want to know...

Kent C. Dodds

Utah

1 wife, 3 kids

PayPal, Inc.

@kentcdodds

Please Stand...

Origin Story

What this talk is

  • Brief history about JavaScript modules
  • Exploration of the ES6 modules standard & syntax
  • More than you probably care to know/will use
  • Lots of code :-)

What this talk is not

  • 100% practical (probably only 90%)

Let's
Get
STARTED!

What is a module?

It's like a chapter in a book.

  • Can have dependencies
  • Can have dependants
  • Encapsulates a topic/logic

A brief history

// globals: please load the add script first 🙏
;(function(global) {
  global.subtract = (a, b) => global.add(a, -b)
})(this)
// AMD: I explicitly depend on './add' 👍
define(['./add'], function(add) {
  return (a, b) => add(a, -b)
});
// CommonJS: I can't do async, but you can bundle me 😀
var add = require('./add')
module.exports = (a, b) => add(a, -b)

ES6 Modules are HERE!!

Sorta...

We can write them

But not load them...

ES6 Modules Spec Goals

  • Default exports are favored
  • Static module structure
  • Support for both synchronous and asynchronous loading
  • Support for cyclic dependencies between modules

Transpilers to the rescue!

Warning!!!

You're about to see transpiled code

I accept the risks...

kcd.im/es6-modules-repo

export default

named export

multiple named exports

named exports + default

named exports as list

named exports as list

with aliases

named export as default

basic import

"run this code"

import default

import named exports

alias imports

import {default}...?

import default as alias

default & named imports

import *

(import all the things)

export *

(export all the things from this other thing)

export {default, foo, bar}

interop require

(thing babel does to make it work with CommonJS modules)

Changes

import {baz} from './foo'
// foo.js
const foo = {baz: 42, bar: false}
export default foo

Babel v5

Babel v6

import foo from './foo'
const {baz} = foo

Resources

Thank you!