Skip to content

JavaScript 模块

ES 模块使用导入 and 导出, named 对比默认导出, and 动态导入.

你将学到

  • Exporting 使用 named and 默认导出
  • Importing named and 默认 bindings
  • Renaming 导入使用 as keyword
  • 动态导入() for lazy 加载
  • 模块作用域, live bindings, and 导入 meta

概念讲解

Why Modules?

Before ES modules, JavaScript had no built-in module system. Developers used patterns like IIFEs, CommonJS (需要/模块.导出), or AMD. ES modules (ESM) are the native standard: each file is a module with its own scope, and you explicitly declare dependencies with 导入 and 导出. This enables tree-shaking, static analysis, and clear dependency graphs.

Named Exports

A named export declares a specific binding that importers must reference by name. You can export declarations inline (导出 函数 foo()) or export a list at the bottom (导出 { foo, bar }). Named exports are preferred for libraries because they are explicit, support autocomplete, and allow importing only what you need.

Default Exports

A module can have at most one default export, imported with any name the importer chooses: 导入 MyComponent 从 './file'. Default exports are convenient for a module's primary purpose (a main class or component) but can reduce refactoring safety because the import name is arbitrary. Many style guides now prefer named exports exclusively.

Renaming and Aggregation

Use as to rename on both sides: 导出 { foo as bar } and 导入 { foo as bar } 从 '...'. A barrel file re-exports from many modules in one place (导出 * 从 './用户'), giving consumers a single import path. Be cautious with 导出 * — it can create name collisions.

Dynamic Import

导入() is a function that returns a promise, loading a module on demand at runtime. This is the basis of code splitting and lazy loading in modern bundlers. Use it to load heavy features only when needed, reducing the initial bundle size. The statically declared 导入 at the top is still preferred for dependencies needed at startup because it enables static analysis and tree-shaking.

示例代码

              // --- math-utils.js (named exports) ---
export const PI = 3.14159;

export function area(radius) {
  return PI * radius ** 2;
}

export function circumference(radius) {
  return 2 * PI * radius;
}

// --- logger.js (default export) ---
export default class Logger {
  constructor(prefix) {
    this.prefix = prefix;
  }
  log(msg) {
    console.log(`[${this.prefix}] ${msg}`);
  }
}

// --- main.js (consuming the modules) ---
// Named import — must match the export names
import { area, circumference } from "./math-utils.js";
// Default import — any name works
import Logger from "./logger.js";
// Renaming a named import
import { PI as TAU_HALF } from "./math-utils.js";

console.log(area(5));        // 78.54
console.log(TAU_HALF);       // 3.14159
new Logger("App").log("started");

// Dynamic import — loads on demand, returns a promise
async function loadHeavyFeature() {
  const { area: lazyArea } = await import("./math-utils.js");
  console.log("Lazy area:", lazyArea(10));
}
loadHeavyFeature();
            

Shows named 导出, 默认导出类, named and 默认导入, renaming 使用 as, and 动态导入() 那个加载模块 on demand 内部异步函数.

动手试一试

  • JSON Formatter

    模块导出经常返回 JSON-如数据 — 格式 and inspect 它.

  • HTTP 请求 Tester

    动态导入是 异步如 获取 — 测试异步加载模式.

常见错误

错误写法

Mixing 上默认 and named 导入语法

正确做法

默认导入有 否 braces: 导入 Logger 从 './logger'. Named 导入 use braces: 导入 { 区域 } 从 './math'. 你能 组合它们: 导入 Logger, { 区域 } 从 './file' 仅如果 file 有两者都.

错误写法

Using circular 导入那个 cause undefined 值

正确做法

如果模块导入 B and B 导入 , one 将 see other's 导出 as undefined 期间 initialization. Break cycle 通过 extracting shared code 到第三模块, or defer cross-access 到函数 call 之后 initialization.

相关速查表

查阅不认识的术语

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

查看术语表

动手做项目

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

查看项目

解读错误信息

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

查看错误