js module
CommonJS and ECMAScript module
JS modules define how we can call functions or access variables in other js files. Those js files become libraries which could be shared.
Node supports two kind of modules: CommonJS and ECMAScript module. ECMAScript module is newer than CommonJS. And now it’s a standard used by browsers and other js runtimes. The key point is how node determines which module system should be used. And the two systems vary in syntax. Check below table:
CommonJS example, run with node index.js
.
// util.js
function f() {
return 1;
}
exports.f = f;
// index.js
const util = require('./util.js');
console.log(util.f());
ECMAScript example, notice that file extension is mjs.
// util.mjs
export function f() {
return 1;
}
// index.mjs
import {f} from './util.js';
console.log(f());
Reference:
https://nodejs.org/dist/latest-v19.x/docs/api/modules.html#modules-commonjs-modules
https://nodejs.org/dist/latest-v19.x/docs/api/packages.html#determining-module-system