Skip to content

模块 and 导入

学习如何 拆分 code 到模块, 导入 and 导出之间 files, and 组织 larger programs effectively.

你将学到

  • 什么模块是 and 为什么它们 matter for code 组织
  • 如何 导出函数, 变量, and 对象从 file
  • 如何 导入什么你 需要从 another 模块
  • 默认导出对比. named 导出
  • 如何模块 prevent 全局命名空间 pollution

概念讲解

Modules and Imports

module 是一种 self-contained file of code that can be shared between different parts of a program. As programs grow, putting everything in one file becomes unmanageable. Modules let you split code into logical units — one file for user functions, another for database helpers, another for UI components — and connect them with imports and exports.

Why Modules?

Without modules, every variable and function lives in the global scope. In a large project, names collide: two files both define a 验证 function, and the second one silently overwrites the first. Modules solve this by giving each file its own scope. Nothing is global unless you explicitly export it.

Modules also make code reusable: you write a utility once in mathUtils.js and import it wherever you need it. And they make code testable: you can import a single module in isolation and verify its behavior without loading the entire application.

Exporting

JavaScript ES modules use the 导出 keyword to share code from a module:

// mathUtils.js
export function add(a, b) { return a + b; }       // named export
export function subtract(a, b) { return a - b; }  // named export
export const PI = 3.14159;                        // named export

// A module can have one default export:
export default function multiply(a, b) { return a * b; }

Importing

Other files bring in the exported code with 导入:

// app.js
import multiply, { add, subtract, PI } from "./mathUtils.js";

add(2, 3);        // 5
multiply(4, 5);   // 20 (default export, no braces)

Named exports are imported with braces: { add, subtract }. The default export is imported without braces and you can rename it freely. A module can have many named exports but only one default.

Default vs. Named Exports

  • Default export — the "主要" thing the module provides. Use it when a module has one primary purpose: 导出 默认 类 用户 { ... }.
  • Named exports — for modules that provide several related utilities. They require exact name matching on import, which helps with autocomplete and refactoring.

Module Resolution

When you write 导入 { x } 从 "./utils", the system resolves the path: ./utils means "in 相同 directory." Node.js and bundlers (Vite, webpack) handle the resolution, finding the right file and connecting the exports to the imports. You just write the path and the names.

Best Practices

Keep modules focused — one module, one responsibility. Prefer named exports for utilities (they are explicit and refactor-safe). Use default exports for the primary class or function a module is built around. Avoid circular dependencies where module A imports module B and B imports A — it creates initialization order problems that are hard to debug.

示例代码

              // --- file: validators.js ---
export function isEmail(text) {
  return text.includes("@") && text.includes(".");
}

export function isPhoneNumber(text) {
  return /^\d{3}-\d{3}-\d{4}$/.test(text);
}

export function minLength(text, n) {
  return text.length >= n;
}

// --- file: formHelpers.js ---
import { isEmail, minLength } from "./validators.js";

export function validateSignupForm(email, password) {
  const errors = [];
  if (!isEmail(email)) errors.push("Invalid email");
  if (!minLength(password, 8)) errors.push("Password too short");
  return errors;
}

// --- file: app.js ---
import { validateSignupForm } from "./formHelpers.js";

const errors = validateSignupForm("[email protected]", "secret");
console.log(errors);  // ["Password too short"]

const valid = validateSignupForm("[email protected]", "securepass");
console.log(valid);   // [] (no errors)
            

validators.js 导出 three named 函数. formHelpers.js 导入 two 的它们 and 导出它的 own 函数. app.js 导入从 formHelpers. 每个 file 有它的 own 作用域 — 否全局 pollution.

动手试一试

  • JSON 到 TypeScript

    TypeScript 接口是 经常 exported 从模块. See 如何数据 shapes 是定义 and shared 跨越 files.

  • Code Minifier

    Minifiers 处理模块 — renaming 内部变量虽然 preserving exported names. See 边界之间内部 and 外部.

常见错误

错误写法

Mixing 上默认 and named 导入语法.

正确做法

默认导入有 否 braces: 导入 x 从 './mod'. Named 导入 use braces: 导入 { x } 从 './mod'. Mixing 它们 causes 语法错误 or undefined 值.

错误写法

创建 circular dependencies (导入 B, B 导入).

正确做法

Refactor 所以 shared code lives in 第三模块那个两者都 and B 导入. Circular dependencies cause undefined 值 at 运行时因为 one 模块是 不 fully initialized 当 other tries 到 use 它.

错误写法

Exporting 一切从 模块, treating 它如 全局 bag 的函数.

正确做法

仅导出什么 other 模块 actually 需要. Keep 内部 helpers unexported. focused 公共 API 制作模块 easier 到理解 and harder 到 misuse.

相关速查表

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

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

查看错误