Node.js模块加载的不同机制有哪些?求专业解答
Hey there! Great question — I totally get why this might be confusing, since Node.js has evolved its module system over time. The three distinct module loading mechanisms you’re hearing about are:
Node.js Module Loading Mechanisms
1. CommonJS (CJS) — The Original Workhorse
This is the module system Node.js launched with, and it’s still the default for .js files unless you configure otherwise.
- Uses
require()to pull in modules, andmodule.exportsorexportsto expose functionality from your own modules - Loads modules synchronously, which works well for server-side initialization where a brief block during startup isn’t a problem
- Modules are cached after the first load, so repeated
require()calls for the same module return the exact same instance - Example code:
// Importing a built-in CJS module const fs = require('fs'); // Exporting from a custom module module.exports = { greet: (name) => `Hello, ${name}!` };
2. ECMAScript Modules (ESM) — The Standardized Modern Approach
Node.js added support for ES6+ modules to align with browser JavaScript and modern JS standards.
- Uses
importandexportsyntax instead ofrequire()/module.exports - Supports asynchronous loading, which is more flexible for dynamic or non-blocking use cases
- To enable ESM in your project, you can either:
- Rename files to use the
.mjsextension - Add
"type": "module"to your rootpackage.json
- Rename files to use the
- Example code:
// Importing a module (using promises for async fs) import { readFile } from 'fs/promises'; // Exporting a function export const double = (num) => num * 2; - ESM has stricter syntax rules (no
require()by default, no implicit file extensions) and a different caching model than CJS.
3. Specialized Native & Static Module Loaders
This third category covers modules that don’t fit neatly into the CJS/ESM paradigm, including:
- JSON Modules: Node.js can directly load
.jsonfiles using eitherrequire()(CJS) orimport(ESM), no manual parsing needed. Example:const config = require('./config.json') - C++ Addons: These are native modules written in C++ that compile to platform-specific binaries. They’re loaded via
require()just like CJS modules, and are used for performance-critical tasks or accessing low-level system APIs. - Built-in Modules: Node.js’s core modules (like
fs,http) are optimized and loaded directly from the Node.js runtime, not from the filesystem. They work seamlessly with both CJS and ESM syntax.
内容的提问来源于stack exchange,提问作者Hemadri Dasari
相关产品推荐
相关产品推荐

