JavaScript Modules Explained

JavaScript

17/04/2023


Nowadays, it's natural to split up a JavaScript program into multiple files, i.e. modules. However, until the ES6 revision in 2015, there was no official support for this. Consequently, unofficial standards emerged, such as CommonJS in NodeJS. Furthermore, a different standard called RequireJS emerged in the browser since CommonJS wasn't designed with browsers in mind.

Consequently, you may have seen import and export statements such as below, which belong to CommonJS.

JAVASCRIPT
var someModule = require("someModule")
function someFunc() {
return someModule.doSomething()
}
modules.exports = someFunc

ES Modules

With the arrival of the official ECMAScript module standard, or short ES Modules, one could now accomplish the same thing in a more readable manner.

JAVASCRIPT
import someModule from "someModule"
function someFunc() {
return someModule.doSomething()
}
export default someFunc

NodeJS

By now, NodeJS has added stable support for ES Modules. However, since CommonJS is the original module system of NodeJS, there is still widespread support for it in the ecosystem. Consequently, in order to not break support, NodeJS still uses it by default.

If you wish to use ES Modules, you can either use it in a .mjs file, set it as the project default with "type": "module" in package.json or use --input-type=module in the CLI. Likewise, NodeJS will treat .cjs files as CommonJS modules.


WRITTEN BY

Code and stuff