当前位置: 首页 > news >正文

TypeScript 中的模块(Modules)详解

TypeScript 中的模块(Modules)详解

模块(Modules)是现代 TypeScript 项目中组织和管理代码的最主要方式。它基于 ES6 的importexport语法(也称为 ES Modules 或 ESM),完全取代了旧的命名空间(namespace)。模块系统让代码具备作用域隔离、按需加载、tree-shaking等优势,是当前所有主流框架(React、Vue、Angular、NestJS、Next.js 等)的标准做法。

1. 基本导出与导入
a. 导出(export)
// file: utils.tsexportfunctionsum(a:number,b:number):number{returna+b;}exportconstPI=3.14159;exportinterfaceUser{name:string;age:number;}exportclassCalculator{multiply(x:number,y:number):number{returnx*y;}}// 默认导出(一个模块只能有一个)exportdefaultfunctiongreet(name:string):string{return`Hello,${name}!`;}
b. 导入(import)
// file: main.tsimportgreetfrom"./utils";// 默认导入import{sum,PI,User,Calculator}from"./utils";// 命名导入import{sumasadd}from"./utils";// 重命名import*asUtilsfrom"./utils";// 导入所有为命名空间对象greet("Alice");// "Hello, Alice!"console.log(sum(2,3));// 5console.log(Utils.PI);letcalc=newCalculator();calc.multiply(4,5);
2. 导出方式总结
方式语法示例说明
命名导出export function fn() {}可导出多个
默认导出export default class MyClass {}一个模块只能一个
重新导出(Re-export)export { name } from "./other";聚合模块
全部重新导出export * from "./utils";导出其他模块的所有(不包括默认导出)
重命名导出export { sum as add } from "./math";
3. 模块路径与解析
  • 相对路径"./utils""../models/user"
  • 绝对路径(需配置baseUrlpaths):
// tsconfig.json{"compilerOptions":{"baseUrl":"./src",// 根目录"paths":{"@utils/*":["utils/*"],// 别名"@components/*":["components/*"]}}}

使用:

import{sum}from"@utils/math";importButtonfrom"@components/Button";
4. 模块模式(Module Mode)

tsconfig.json中配置:

配置值输出格式适用环境
"ESNext""ES2022"原生 ES Modules现代浏览器、Vite、Deno、Bun
"CommonJS"require/module.exportsNode.js(传统)
"AMD"/"UMD"/"System"旧模块系统老项目

推荐:现代项目统一使用"ESNext"+"moduleResolution": "node""nodenext"

5. 动态导入(Dynamic Import)—— 按需加载

返回 Promise,适合代码分割、懒加载:

// 静态导入(打包时一起加载)import{heavyFunction}from"./heavy";// 动态导入(运行时加载)asyncfunctionloadHeavy(){constmodule=awaitimport("./heavy");module.heavyFunction();}button.addEventListener("click",loadHeavy);
6. 类型声明模块(Declaration Files)

为非 TS 文件(如.js、第三方库)提供类型:

// file: declarations/jquery.d.tsdeclaremodule"jquery"{exportdefaultfunction$(selector:string):any;}// 使用import$from"jquery";$("#app").html("Hello");

或全局声明:

// file: globals.d.tsdeclareglobal{interfaceWindow{myGlobalVar:string;}}
7. 侧边模块增强(Module Augmentation)

扩展第三方库的类型(常见于 lodash、express 等):

// file: types/express.d.tsimport"express";declaremodule"express"{interfaceRequest{user?:{id:number;name:string};}}// 现在所有 express Request 都有 user 属性类型提示
8. 常见模块使用场景
场景推荐方式
工具函数一个文件导出多个函数
React 组件export default function Component()
类型/接口单独文件导出多个 interface/type
常量配置export const CONFIG = { ... }
聚合导出(barrel)index.tsexport * from "./xxx"
Node.js 服务端"module": "ESNext"+.mjs"type": "module"
9. 最佳实践建议
建议说明
一个文件一个责任每个文件导出相关的一组内容
优先默认导出组件React/Vue 等组件用export default
类型单独文件interfaces/types 放types/或单独.d.ts
使用路径别名配置@utils/*等,提高可读性
避免循环依赖模块相互 import 会导致问题
barrel 文件谨慎使用export * from过多影响 tree-shaking
开启"isolatedModules": true确保兼容 Babel、esbuild 等工具
小结:模块 vs 命名空间
特性模块 (import/export)命名空间 (namespace)
现代推荐强烈推荐已过时
作用域文件级隔离全局或嵌套
加载方式静态/动态,按需脚本加载
tree-shaking支持不支持
声明文件支持常用于旧库

结论:在 2025 年的 TypeScript 开发中,所有新项目都应使用 ES 模块系统。命名空间仅用于维护旧代码或特定声明文件场景。

如果您想看实际项目结构示例(如 React + Vite 的模块组织、Next.js 的页面模块、Node.js 的服务模块),或者想了解如何配置 tsconfig 支持模块,请告诉我!

http://www.jsqmd.com/news/118487/

相关文章:

  • 22、Windows Server 2003 集群与负载均衡:SQL Server 2000 集群解决方案全解析
  • Excalidraw AI生成图表后的手动精细化调整
  • 为什么你的回滚总失败?(Open-AutoGLM操作日志还原实战揭秘)
  • Excalidraw图形语义理解模型训练思路
  • 【亲测】迅雷2025 Beta【25.0.1.1036】绿色精简版【2025年12月最新版】
  • 23、Visual Studio 2010 中 SharePoint 内容类型的使用与高级操作
  • Open-AutoGLM拖拽式开发十大技巧(90%工程师不知道的隐藏功能)
  • Excalidraw AI推动可视化教育普及的意义
  • 揭秘Open-AutoGLM可视化引擎:如何3步完成复杂模型部署?
  • TypeScript 类
  • Open-AutoGLM版本管理陷阱,3大高频故障场景下的精准回滚策略
  • 24、SharePoint 内容类型与工作流深度解析
  • Excalidraw AI生成内容的合规性审查机制
  • 别再手动调试了!5个Open-AutoGLM自动化脚本让你效率翻倍
  • 中学应有的几何起码常识让2500年都无人能识的“更无理”数一下子浮出水面推翻“R完备、封闭”论
  • 为什么顶尖团队都在用Open-AutoGLM?一文看懂其架构设计精髓
  • 25、SharePoint工作流:全面指南
  • Obsidian使用学习
  • Excalidraw AI无法识别指令怎么办?常见问题解答
  • Excalidraw AI生成结果的人工审核流程
  • 13、Windows 2000与Windows Server 2003集群及负载均衡配置详解
  • 26、深入了解 SharePoint 工作流:从设计到导入
  • Open-AutoGLM模板怎么用?99%人都不知道的4个隐藏技巧
  • Excalidraw AI推理对GPU算力的需求评估
  • 还在写代码搭流程?Open-AutoGLM拖拽式方案让你领先同行3年
  • Excalidraw AI服务按Token计费模式探讨
  • 14、升级到 Windows Server 2003 集群解决方案的全面指南
  • 2025年12月企业管理咨询公司如何选?十大顶尖机构多维对比与避坑推荐 - 十大品牌推荐
  • TypeScript 条件语句
  • 15、深入解析Windows Server 2003集群服务的规划与配置