A module is a JavaScript unit that exports objects (such as functions or variables) (export
keyword).
Modules are fetched using CORS.
ES Modules vs CommonJS
The ECMS standard (ES) is the official standard to package JavaScript for reuse. The corresponding keywords are export
and import
.
CommonJS is the original way to package JavsScript for Node.js. The corresponding keywords are
module.exports
and
require()
.
Node version 13.2.0 has ES modules (as well?).
In order for Node.js to treat a module as ES module, there are three possibilities:
- use
.mjs
file suffix
- use the
type
field with a value of module
in package.json
- use the
--input-type=module
command line option
The suffix .cjs
is used to mark a file as a CommonJS module.
ES Module:
import pkg from 'moduleName'
CommonJS:
module.exports.sym = …;
const pkg = require('moduleName')