CommonJS Let’s see 2 examples in CommonJS:
1 2 3 4 5 6 var count = 0 ;exports.up = function ( ) { return ++count; } exports.count = count;
1 2 3 4 5 6 var lib = require ('./lib' );console .log(lib.count); console .log(lib.up()); console .log(lib.count);
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 var count = 0 ;exports.up = function ( ) { return exports.count = ++count; } exports.count = count;
The follow example may looks better.
1 2 3 4 5 6 7 8 var out = { count: 0 , up: function ( ) { return ++out.count; } }; module .exports = out;
1 2 3 4 5 6 var lib = require ('./lib.2' );console .log(lib.count); console .log(lib.up()); console .log(lib.count);
ES2015 modules It’s simple to make Example 2 works in ES2015:
1 2 3 4 5 6 7 8 9 export let count = 0 ;export function up ( ) { return ++count; }; export function unused ( ) { return --count; }
1 2 3 4 5 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
:
1 2 3 4 5 6 7 8 9 10 11 "use strict" ;Object .defineProperty(exports, "__esModule" , { value: true }); exports.up = up; var count = exports.count = 0 ;function up ( ) { return exports.count = count += 1 ; };
1 2 3 4 5 6 7 8 'use strict' ;var _lib = require ('./lib' );console .log(_lib.count); 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' ;let count = 0 ;function up ( ) { return ++count; }; console .log(count);console .log(up());console .log(count);
Read More