Modules in CommonJS and ES2015

CommonJS

Let’s see 2 examples in CommonJS:

  • Example 1
1
2
3
4
5
6
// ----- lib.js -----
var count = 0;
exports.up = function () {
return ++count;
}
exports.count = count;
1
2
3
4
5
6
// ----- main.js -----
var lib = require('./lib');

console.log(lib.count); // 0
console.log(lib.up()); // 1
console.log(lib.count); // 0

In this case, lib.count in main.js would not change after function lib.up called. In lib.js we can see, count is a number, which is primitive, so is exports.count. Thus, exports.count won’t change when we change count. We can change it to make a different:

1
2
3
4
5
6
// ----- lib.change.js -----
var count = 0;
exports.up = function () {
return exports.count = ++count;
}
exports.count = count;

The follow example may looks better.

  • Example 2
1
2
3
4
5
6
7
8
// ----- lib.2.js -----
var out = {
count: 0,
up: function () {
return ++out.count;
}
};
module.exports = out;
1
2
3
4
5
6
// ----- main.2.js -----
var lib = require('./lib.2');

console.log(lib.count); // 0
console.log(lib.up()); // 1
console.log(lib.count); // 1

ES2015 modules

It’s simple to make Example 2 works in ES2015:

1
2
3
4
5
6
7
8
9
// ----- lib.js -----
export let count = 0;
export function up() {
return ++count;
};

export function unused() {
return --count;
}
1
2
3
4
5
// ----- main.js -----
import { count, up } from './lib';
console.log(count);
console.log(up());
console.log(count);

Babel

Using Babel and babel-preset-es2015 make it similar to our lib.change.js:

  • babel lib.js
1
2
3
4
5
6
7
8
9
10
11
"use strict";

Object.defineProperty(exports, "__esModule", {
value: true
});
exports.up = up;
// ----- lib.js -----
var count = exports.count = 0;
function up() {
return exports.count = count += 1;
};
  • babel main.js
1
2
3
4
5
6
7
8
'use strict';

var _lib = require('./lib');

console.log(_lib.count); // ----- main.js -----

console.log((0, _lib.up)());
console.log(_lib.count);

Rollup

Rollup bundle up with less code:

1
2
3
4
5
6
7
8
9
10
11
'use strict';

// ----- lib.js -----
let count = 0;
function up() {
return ++count;
};

console.log(count);
console.log(up());
console.log(count);

Read More