ECMAScript Modules (ESM)

ECMAScript Modules (ESM)

Import and export modules

·

2 min read

To import or export code between files, JavaScript uses two module systems. Node.js has been using the older CommonJS (CJS) module system, while the newer ECMAScript (ESM) modules have been added to the JavaScript specification and are supported by browsers. Node.js is also adding support for ESM.

CommonJS

At the moment, Node.js uses CommonJS (also known as CJS) modules to import and export dependencies.

//export
// example/index.cjs (.cjs is suffix for CommonJS)
module.exports = {
  propery1: "value1",
  propery2: "value2"
}; 

//import
//index.cjs
const examples = require("example"); //it contains both fields   
const { propery1, propery2 } = require("example"); // importing individual property

ESM

ECMAScript Module uses a different approach to import and export modules.

//import
// example/index.mjs 
export const propery1 = "value1";
export const propery2 = "value2";
export default { propery3: "value3" };

//export
// index.mjs
import propery3 from "example";          // _Only_ `default` export (`{ propery3 }`)
import { propery1, propery2 } from "example";   // Other named exports

CommonJS has been part of Node.js since its beginning, but it does not allow module introspection. Starting with Node.js v12.17.0, ESM support is available to all Node.js applications without experimental flags.

Features

  • Module imported has package.json file with field "type": "module".

  • Imported file name ends with .mjs.

  • package.json has filed "exports" to handles how node.js import files.

{
  // package.json
  "name": "example",
  "type": "module",
  "main": "src/main.js",
  "exports": {
    ".": "./src/main.js"
  }

Self-referencing the package

This is code from the existing package, yet it can self-reference itself using the name of the package, instead of using ../src/main.js.

References