Modules
Node Modules - CJS
node-modules
├── lib.js
└── main.js
function sum(a, b) {
return a + b;
}
module.exports = sum;
const sum = require('./lib.js');
console.log(sum(1, 2)); //=> 3
$ node main.js
ECMAScript Modules
Default export
default-export
├── lib.mjs
└── main.mjs
node-esm/default-export/lib.mjs:
export default function sum(x, y) {
return x + y;
}
node-esm/default-export/main.mjs:
import sum from './lib.mjs';
console.log(sum(10, 5)); //=> 15
$ node --experimental-modules main.mjs
Default and named exports
default-named-exports
├── lib.mjs
└── main.mjs
node-esm/default-named-exports/lib.mjs:
export default function sum(x, y) {
return x + y;
}
export function minus(x, y) {
return x - y;
}
node-esm/default-named-exports/main.mjs:
import sum, { minus } from './lib.mjs';
console.log(sum(10, 5)); //=> 15
console.log(minus(10, 5)); //=> 5
$ node --experimental-modules main.mjs
Named as exports
default-as-exports
├── lib.mjs
└── main.mjs
node-esm/named-as-exports/lib.mjs:
export function sum(x, y) {
return x + y;
}
export function minus(x, y) {
return x - y;
}
node-esm/named-as-exports/main.mjs:
import * as lib from './lib.mjs';
console.log(lib.sum(10, 5)); //=> 15
console.log(lib.minus(10, 5)); //=> 5
$ node --experimental-modules main.mjs
Named export
named-export
├── lib.mjs
└── main.mjs
node-esm/named-export/lib.mjs:
export function sum(a, b) {
return a + b;
}
node-esm/named-export/main.mjs:
import { sum } from './lib.mjs';
console.log(sum(1, 2)); //=> 3
$ node --experimental-modules main.mjs
Named exports
named-exports
├── lib.mjs
└── main.mjs
node-esm/named-exports/lib.mjs:
export function sum(x, y) {
return x + y;
}
export function minus(x, y) {
return x - y;
}
node-esm/named-exports/main.mjs:
import { sum, minus } from './lib.mjs';
console.log(sum(10, 5)); //=> 15
console.log(minus(10, 5)); //=> 5
$ node --experimental-modules main.mjs
Named uniq export
named-uniq-export
├── lib.mjs
└── main.mjs
node-esm/named-uniq-export/lib.mjs:
function sum(x, y) {
return x + y;
}
function minus(x, y) {
return x - y;
}
export { sum, minus };
node-esm/named-uniq-export/main.mjs:
import { sum, minus } from './lib.mjs';
console.log(sum(10, 5)); //=> 15
console.log(minus(10, 5)); //=> 5
$ node --experimental-modules main.mjs
Named uniq export alias
named-uniq-export-alias
├── lib.mjs
└── main.mjs
node-esm/named-uniq-export-alias/lib.mjs:
const squareRoot = Math.sqrt;
function sum(x, y) {
return x + y;
}
function minus(x, y) {
return x - y;
}
export { sum, minus, squareRoot as sqrt };
node-esm/named-uniq-export-alias/main.mjs:
import { sum, sqrt } from './lib.mjs';
console.log(sum(10, 5)); //=> 15
console.log(sqrt(100)); //=> 10
$ node --experimental-modules main.mjs