How Node.js Distinguishes ES Modules from CommonJS After Dropping --experimental-modules
Node.js 13.2.0 removes the experimental flag, making ES module support stable and defining clear rules—file extensions, package.json type fields, and runtime flags—to decide whether a file is loaded as an ES module or a CommonJS module.
Node.js 13.2.0, released on the 21st of this month, removed the --experimental-modules flag, indicating that ES module support has moved to a more stable stage.
Node.js distinguishes ES modules from CommonJS modules in the following cases:
File extension is .mjs.
The type field in package.json is set to "module".
The runtime is started with --input-type=module.
In all other situations the file is treated as a CommonJS module.
Conversely, a file is forced to be recognized as CommonJS when any of these conditions are met:
File extension is .cjs.
The type field in package.json is set to "commonjs".
The runtime is started with --input-type=commonjs.
Example:
// package.json contains "type": "module"
import './test/aaa.js'; // aaa.js is loaded as an ES module because the current package.json has type=module
import 'test-aaa'; // loading depends on test-aaa's own package.json type field
import './node_modules/test-aaa/index.js'; // same logic appliesThe official documentation currently marks this feature with “Stability: 1”, meaning it is still experimental, but the removal of the flag suggests it will soon reach “Stability: 2” and become fully stable.
For more details, refer to the original Node.js 13.2.0 ESM documentation.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Node Underground
No language is immortal—Node.js isn’t either—but thoughtful reflection is priceless. This underground community for Node.js enthusiasts was started by Taobao’s Front‑End Team (FED) to share our original insights and viewpoints from working with Node.js. Follow us. BTW, we’re hiring.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
