CommonJS (Cjs)
Definition
- CommonJS is synchronous. Use in a Node.js environment
- By default, CommonJS file name is
.cjs
, or.js
by default will be interpreted as CommonJS.- Note: unless you want to specifically state that the file only support CommonJS format, use
.cjs
since Node.js now also support ES6 format with version 13 and above with"type": "module"
inpackage.json
or just name the file.mjs
- Note: unless you want to specifically state that the file only support CommonJS format, use
- CommonJS syntax can be used in browser with the support of RequireJS or BrowserifyJS
Syntax
Export
// src/index.js
class Logger {
log(content) {
console.log(content)
}
}
module.exports = new Logger()
Import
// index.js
var Logger = require('./src/logger.js')
var data = [1, 2, 2, 3, 4, 5, 5, 5, 6];
Logger.log(data);
Execution
Node.js
node index.js
Browser
To run CommonJS syntax in the browser, we can consider
- RequireJS: Support
require()
syntax in browser - UMD: Support both browser and NodeJS
- BalbelJS: Bundle everything with a compilation before injecting inside browser
- SystemJS: Universal loader that support CommonJS (CJS), UMD and ECMAScript Module (ESM)