Notes of ES Modules and CommonJS Modules

Notes of ES Modules and CommonJS Modules

Node

Node version: v8.5.0

  • Node Modules
  • Node ECMAScript Modules
  • Node EP for ES Modules

  • The --experimental-modules flag can be used to enable features for loading ES modules
  • ES modules imports will be loaded asynchronously
  • ES modules files will use .mjs extension
  • The .mjs file extension will not be loadable via require()

ES consuming CommonJS

cjs.js:

1
2
module.exports = { v: 1 }
module.exports.f = () => 2

esm.mjs:

1
2
3
4
5
import assert from 'assert'
import cjs from './cjs'

assert.equal(cjs.v, 1)
assert.equal(cjs.f(), 2)

Unsupported Features

  • import()
  • import.meta
  • Loader Hooks

Babel Transform Plugin

Babel version: v6.26.0 Babel plugin transform-es2015-modules-commonjs

Export

In:

1
2
export default { v: 1 }
export const f = () => 2

Out:

1
2
3
Object.defineProperty(exports, '__esModule', { value: true })
exports.default = { v: 1 }
const f = exports.f = () => 2

Import

In:

1
2
3
import x from 'x'

x.v

Out:

1
2
3
4
5
6
7
8
9
10
11
const __x = require('x')

const _x = _interopRequireDefault(__x)

const x = _x.default

function _interopRequireDefault(o) {
return o && o.__esModule ? o : { default: o }
}

x.v

In:

1
2
3
import { y } from 'y'

y.v

Out:

1
2
3
4
5
const _y = require('y')

const y = _y.y

y.v

In:

1
2
3
import * as z from 'z'

z.v

Out:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const _z = require('z')

const z = _interopRequireWildcard(_z)

function _interopRequireWildcard(o) {
if (o && o.__esModule) {
return o
} else {
const m = {}
if (o != null) {
for (let key in o) {
if (Object.prototype.hasOwnProperty.call(o, key))
m[key] = o[key]
}
}
m.default = o
return m
}
}

z.v