1. 模块的定义
- 任何包含顶层 import 或 export 语句的文件都被视为模块
- 模块在自己的作用域内执行,而非全局作用域
- 没有导入导出语句的文件被视为脚本,其内容在全局作用域中可用
2. ES 模块语法
- 使用 import 和 export 关键字进行模块的导入和导出
- 支持命名导出(export const pi = 3.14)和默认导出(export default function)
- 支持通配符导入(import * as math from "./math")和重命名导入(import { pi as π } from "./math")
- 支持类型导入(import type { Cat } from "./animal"),仅导入类型而不导入运行时代码
3. CommonJS 语法
- 使用 module.exports 导出和 require() 导入
- 主要应用于 Node.js 传统项目
- TypeScript 可以根据 module 配置选项自动在 ES 模块和 CommonJS 之间转换
4. 模块解析策略
- 相对路径导入:以 ./ 或 ../ 开头,从当前文件位置解析
- 非相对路径导入:从 node_modules 中查找,或通过 baseUrl 和 paths 配置的路径别名解析
- TypeScript 会按顺序查找:.ts、.tsx、.d.ts 文件,或 package.json 中的 types/typings 字段
- node/node16/nodenext 解析策略模拟 Node.js 的模块解析行为
- bundler 解析策略适用于 Webpack、Vite 等打包工具
5. 声明文件的模块声明
- 使用 declare module "module-name" 为没有类型定义的 JavaScript 模块声明类型
- 可以在声明文件中描述模块的导出结构,实现类型安全
- 支持通配符声明,如 declare module "*.svg" 匹配所有 SVG 导入