Skip to content

模块

一句话解释

模块 是 self-包含 file 的 code 那个 能 导出 值 and 导入 它们 从 other 模块.

用大白话说

模块是 file 的 JavaScript code 那个 encapsulates 它的内容 and 能 share 特定部分使用 other files. 你 mark 什么是 公共使用 export and consume 它 elsewhere 使用 import. This lets you split a large program into small, focused files.

Before native modules, JavaScript relied on patterns like IIFEs and libraries such as CommonJS (需要) or AMD. ES modules (ESM) are the native standard: 导出函数添加() in one file, 导入 { 添加 } 从 "./math.js" in another. Modern browsers and Node.js both support ESM.

Modules have their own scope — top-level variables in a module are not global. Each module is imported at most once, even if multiple files import it, so its top-level code runs a single time. This makes modules a clean way to organize and reuse code.

示例

javascript
// math.js
export function add(a, b) {
  return a + b;
}

// main.js
import { add } from "./math.js";

console.log(add(2, 3)); // 5

math.js 导出 添加; 主要.js 导入 它. 每个 file 是 模块 使用 它的 own 作用域.

常见混淆

  • 容易混淆的对象: 包

    关键区别: 模块 是 单个 file (or folder 使用 条目 点) 的 code 你 导入; 包 是 distributable 单元 (经常 从 npm) 那个 可能 包含 许多 模块 plus metadata. 所有 包 包含 模块, 但 模块 是 不 necessarily 包.

相关术语

相关资源

相关课程

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表