惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
Securelist
C
CERT Recently Published Vulnerability Notes
Forbes - Security
Forbes - Security
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
L
LINUX DO - 最新话题
The Hacker News
The Hacker News
Google Online Security Blog
Google Online Security Blog
SecWiki News
SecWiki News
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
The Last Watchdog
The Last Watchdog
S
Schneier on Security
T
Troy Hunt's Blog
N
News | PayPal Newsroom
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Schneier on Security
Schneier on Security
P
Privacy & Cybersecurity Law Blog
T
Tor Project blog
T
Threatpost
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
A
Arctic Wolf
S
Secure Thoughts
P
Proofpoint News Feed
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Security Latest
Security Latest
Scott Helme
Scott Helme
Security Archives - TechRepublic
Security Archives - TechRepublic
Latest news
Latest news
PCI Perspectives
PCI Perspectives
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Hacker News - Newest:
Hacker News - Newest: "LLM"
L
LINUX DO - 热门话题
P
Palo Alto Networks Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
G
GRAHAM CLULEY
V2EX - 技术
V2EX - 技术
Google DeepMind News
Google DeepMind News
Project Zero
Project Zero
V
Vulnerabilities – Threatpost
T
Threat Research - Cisco Blogs
Webroot Blog
Webroot Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
N
News and Events Feed by Topic
TaoSecurity Blog
TaoSecurity Blog
大猫的无限游戏
大猫的无限游戏
T
Tenable Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
V
Visual Studio Blog
H
Hacker News: Front Page
Simon Willison's Weblog
Simon Willison's Weblog
AWS News Blog
AWS News Blog

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
How to Use ES Modules in Node.js
Dmitri Pavlutin · 2021-04-27 · via Dmitri Pavlutin Blog

The ECMAScript modules (in short ES modules) is a JavaScript modules format that uses import and export statements:


// An ECMAScript module

// import statement

import myFunc from './my-func';

// export statement

export myOtherFunc(param) {

const result = myFunc(param);

// ....

return otherResult;

}


Starting version 13.2.0, Node.js has stable support of ES modules.

In this post, you'll learn how to enable and use ES modules in Node.js.

Table of Contents

  • 1. Enabling ECMAScript modules in Node.js
    • 1.1 .mjs file extension
    • 1.2 { "type": "module" } in package.json
  • 2. Importing ECMAScript modules
    • 2.1 Relative specifier
    • 2.2 Bare specifier
    • 2.3 Absolute specifier
  • 3. Dynamic import of modules
  • 4. Mixing module formats
  • 5. ECMAScript modules and Node.js environment
  • 6. Conclusion

1. Enabling ECMAScript modules in Node.js

The default format of modules in Node.js is the CommonJS.

But Node.js will treat a JavaScript file as an ECMAScript modules format if:

  1. The module's file extension is .mjs
  2. Or the module's nearest parent folder has { "type": "module" } in package.json
  3. Or the argument --input-type=module is present, and the module's code is passed as a string using --eval="<module-code>" argument or from STDIN.

Let's detail into the first (.mjs extension) and second ({ "type": "module" } in package.json) ways.

1.1 .mjs file extension

If you create a JavaScript file with the extension .mjs, then Node.js will consider the file an ES module.

The following ES module month-from-date.mjs (note the .mjs file extension) exports a function monthFromDate(), which determines the month name of an arbitrary date:


// month-from-date.mjs (ES Module)

const MONTHS = ['January', 'February', 'March','April', 'May', 'June',

'July', 'August', 'September', 'October', 'November', 'December'];

export function monthFromDate(date) {

if (!(date instanceof Date)) {

date = new Date(date);

}

return MONTHS[date.getMonth()];

}


Same way another module month.mjs uses the ES module import syntax to import monthFromDate() function from 'month-from-date.mjs' module. This module also runs as a CLI script, and prints the month name of the date string passed as an argument:


// month.mjs (ES Module)

import { monthFromDate } from './month-from-date.mjs';

const dateString = process.argv[2] ?? null;

console.log(monthFromDate(dateString));


That's all you need to make Node.js use ES modules!

Let's run month.mjs module in command line:


node ./month.mjs "2022-02-01"


Run the command in the demo.

February is printed in the terminal.

1.2 { "type": "module" } in package.json

By default .js files in Node.js are considered CommonJS modules. To make .js files as ES modules simply set "type" field as "module" in the package.json:


{

"name": "my-app",

"version": "1.0.0",

"type": "module",

// ...

}


Now all .js files inside the folder containing such package.json execute as ECMAScript modules.

Regarding the month modules, let's rename month-from-date.mjs to month-from-date.js and month.mjs to month.js (while still keeping the import and export syntax), set "type" field as "module" in the package.json, and Node.js is going to execute these modules as ECMAScript ones.


node ./month.js "2022-03-01"


Run the command in the demo.

March is printed in the terminal. Node.js ran successfully the ES modules month.mjs and month-from-date.mjs.

2. Importing ECMAScript modules

The specifier is the string literal having the path from where to import the module.

In the example below 'path' is a specifier:


// 'path' is the specifier

import module from 'path';


There are 3 kinds of specifiers in Node.js: relative, bare and absolute.

2.1 Relative specifier

Importing a module using a relative specifier resolves the path of the imported module relative to the current (importing) module location.

Relative specifiers usually start with '.', '..', or './':


// Relative specifiers:

import module1 from './module1.js';

import module2 from '../folder/module2.mjs';


When using relative specifiers indicating the file extension (.js, .mjs, etc.) is obligatory.

2.2 Bare specifier

A bare specifier starts with a module name (doesn't start with '.', './', '..', '/'), and imports modules from node_modules or the built-in Node.js modules.

For example, if you've installed the lodash-es package in node_modules, then you can access that module using a bare specifier:


// Bare specifiers:

import lodash from 'lodash-es';

import intersection from 'lodash-es/intersection';


Using bare specifiers you can also import the Node.js built-in modules:

2.3 Absolute specifier

An absolute specifier imports modules using an absolute path:


// Absolute specifier:

import module from 'file:///usr/opt/module.js';


Note the presence of the file:// prefix in the absolute specifiers.

3. Dynamic import of modules

The default importing mechanism of ES modules always evaluates the imported module: no matter if you use the module or not.

If you want to import the modules dynamically, then invoke the asynchornous function import('./path-to-module'):


async function loadModule() {

const {

default: defaultComponent,

component1

} = await import('./path-to-module');

// ...

}

loadModule();


import('./path-to-module') loads asynchronously the module. import() returns a promise that resolves to the imported module components:

  • default property as the default import
  • the named imports as properties with the same names

For example, let's improve month.js script to load month-from-date.js module only when the user sets the date argument:


// month.js (ES Module)

const dateString = process.argv[2] ?? null;

if (dateString === null) {

console.log('Please indicate date argument');

} else {

(async function() {

const { monthFromDate } = await import('./month-from-date.js');

console.log(monthFromDate(dateString));

})();

}


const { monthFromDate } = await import('./month-from-date.mjs') loads the module dynamically, and assigns the named export monthFromDate to a variable with the same name.


node ./month.js "2022-04-01"


Run the command in the demo.

April is logged in the terminal.

4. Mixing module formats

You can be in a situation when you need to import a CommonJS module from an ES module, and vice-versa.

Fortunately, Node.js allows an ES module to include a CommonJS module as a default import:


// ES module

import defaultComponent from './module.commonjs.js';

// ...


When imported in an ES module, the module.exports of the CommonJS module becomes the default import. The named imports from a CommonJS module, however, is not supported.

The require() function of the CommonJS format cannot import an ES module. Instead, you can use the async function import() inside CommonJS to load an ES module:


// CommonJS module

async function loadESModule() {

const {

default: defaultComponent,

component1

} = await import('./module.es.mjs');

// ...

}

loadESModule();


I recommend as much as possible to avoid mixing module formats because it is confusing.

5. ECMAScript modules and Node.js environment

Inside the ECMAScript module scope are not available the CommonJS specific variables like:

  • require()
  • exports
  • module.exports
  • __dirname
  • __filename

However, you can use import.meta.url to determine the absolute path of the current module:


// An ES module at path "/usr/opt/module.mjs"

console.log(import.meta.url); // "file:///usr/opt/module.mjs"


6. Conclusion

Node.js supports ES modules when the module extension is .mjs, or the nearest folder of the module has a package.json containing { “type”: “module” }.

Then you can import modules using:

  • Relative path, e.g. import module from './module.js'
  • Absolute path, e.g. import module from 'file:///abs/path/module.js'
  • Modules installed in node_modules, e.g. import lodash from 'lodash-es'
  • Or built-in Node.js modules like import fs from 'fs'.

You can import dynamically a module using import('./path-to-module') syntax.

While not desirable, but sometimes necessary, you can import a CommonJS module from an ES module using the import defaultImport from './common.js' statement. The module.exports of the CommonJS becomes the default import defaultImport inside the ES module.

How to write quality ECMAScript modules? To find out, follow my post 4 Best Practices to Write Quality JavaScript Modules.

Do you think Node.js should migrate completely to ES modules format?