Bindings

Rich Harris edited this page May 26, 2015 · 1 revision

ES6 modules export bindings, not values. Consider the following CommonJS:

// counter.js
var count = 0;
function increment () {
  count += 1;
}

exports.count = count;
exports.increment = increment;

// app.js
var counter = require( './counter' ),
    count = counter.count,
    increment = counter.increment;

console.log( count ); // 0
increment();
console.log( count ); // still 0!

Hopefully the result of that experiment wasn't a surprise to you: at the point at which count was assigned to exports, the value was fixed. Even if it wasn't, count = counter.count fixes the value on the importer side of the equation.

With ES6, we see different results:

// counter.js
export var count = 0;
export function increment () {
  count += 1;
}

// app.js
import { count, increment } from './counter';

console.log( count ); // 0
increment();
console.log( count ); // 1