详解 Node.js 模块系统
探索 CommonJS 模块和 ES 模块,了解如何在 Node.js 的不同文件之间导入和导出功能。
详解 Node.js 模块系统 是 CoddyKit 上的免费 Node.js Backend Development Bootcamp 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Node.js Backend Development Bootcamp 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Node.js Backend Development Bootcamp 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Organize Your Code with Modules
As apps grow, one giant file gets messy. Modules split code into small, reusable, focused pieces. Node supports two systems: CommonJS and ES Modules.
CommonJS: `require()` & `module.exports`
CommonJS is Node's original module system: require() pulls code in, module.exports pushes code out. Import what you need, export what you offer.
CommonJS: Exporting a Function
Here's mathUtils.js. Whatever you assign to module.exports is what other files can import from it — here, just the add function.
const add = (a, b) => a + b;
const subtract = (a, b) => a - b;
module.exports = add; // Only 'add' is exportedCommonJS: Importing and Using
In another file, require('./mathUtils.js') pulls in that exported function. Keep both files in the same folder and run node app.js.
const addFunction = require('./mathUtils.js');
console.log("Using the imported function:");
console.log(`5 + 3 = ${addFunction(5, 3)}`);
console.log(`10 + 2 = ${addFunction(10, 2)}`);CommonJS: Exporting Multiple Items
Need to export several things? Assign an object to module.exports holding all of them — a clean way to group related utilities.
const greet = (name) => `Hello, ${name}!`;
const farewell = (name) => `Goodbye, ${name}!`;
module.exports = {
greetUser: greet,
sayGoodbye: farewell
};CommonJS: Importing Multiple Items
When a module exports an object, grab pieces with destructuring: const { greetUser, sayGoodbye } = require(...). Cleaner and clearer than dot access.
const { greetUser, sayGoodbye } = require('./utils.js');
console.log(greetUser('Alice'));
console.log(sayGoodbye('Bob'));ES Modules: The Modern Standard
ES Modules (ESM) are JavaScript's official standard, using import/export. They enable tree-shaking — set "type": "module" or use .mjs to opt in.
ESM: Named Exports & Imports
With named exports, you export values by name and import them in matching { } braces — making it obvious exactly which parts you're using.
export const add = (a, b) => a + b;
export const multiply = (a, b) => a * b;
// app.mjs (main entry point)
// To run this: ensure package.json has "type": "module"
// and run with `node app.mjs`
import { add, multiply } from './calculator.mjs';
console.log(`2 + 4 = ${add(2, 4)}`);
console.log(`5 * 6 = ${multiply(5, 6)}`);ESM: Default Exports
A module can have one default export, usually its main feature. Import it under any name you like, no braces needed.
const logMessage = (msg) => console.log(`[LOG] ${msg}`);
export default logMessage;
// main.mjs (main entry point)
// To run this: ensure package.json has "type": "module"
// and run with `node main.mjs`
import myLogger from './logger.mjs';
myLogger('This is a default message.');
myLogger('Another important event.');Quick Check: Module Systems
You've learned about CommonJS and ES Modules. Let's test your understanding!
Recap: Node.js Modules
You've explored Node modules: CommonJS (require/module.exports, the classic) and ESM (import/export, the modern standard). Both keep apps organized.
常见问题解答
「详解 Node.js 模块系统」课时是免费的吗?
是的 — 「详解 Node.js 模块系统」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Node.js Backend Development Bootcamp 课程的其余内容,请升级到 CoddyKit PRO。 Node.js Backend Development Bootcamp 课程共包含 4 节课。
「详解 Node.js 模块系统」这节课中我会学到什么?
探索 CommonJS 模块和 ES 模块,了解如何在 Node.js 的不同文件之间导入和导出功能。 你通过在浏览器中直接运行的动手代码来练习 Node.js Backend Development Bootcamp,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Node.js Backend Development Bootcamp 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Node.js Backend Development Bootcamp 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「详解 Node.js 模块系统」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Node.js Backend Development Bootcamp 课中编写并运行代码吗?
能。每节 Node.js Backend Development Bootcamp 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- Node.js 与 NPM 入门
- 详解 Node.js 模块系统
- 异步 JavaScript 与事件循环
- 使用文件系统与流