文章目录

TypeScript 包管理:package.json 与 tsconfig.json

发布于 2026-04-10 04:20:15 · 浏览 7 次 · 评论 0 条

TypeScript 包管理:package.json 与 tsconfig.json

TypeScript 项目的核心在于两个配置文件:package.json 负责项目的依赖管理和脚本定义,tsconfig.json 负责 TypeScript 编译器的行为控制。理解并正确配置这两个文件,是搭建稳健开发环境的第一步。


1. 配置 package.json:管理依赖与脚本

package.json 是项目的身份证,它记录了项目名称、版本以及运行所需的第三方库。

打开 终端,进入 项目根目录,执行 以下命令初始化文件:

npm init -y

编辑 生成的 package.json 文件,重点关注以下字段。

1.1 核心依赖字段

区分 dependenciesdevDependencies 是项目规范的关键。

字段名 用途说明 典型场景
dependencies 生产环境依赖。代码运行时必须的库,打包后会部署到服务器。 express, lodash, react
devDependencies 开发环境依赖。仅在开发、编译、测试阶段使用,不会部署到服务器。 typescript, eslint, @types/node

安装 生产环境依赖(例如 express):

npm install express

安装 开发环境依赖(例如 typescript):

npm install -D typescript

1.2 脚本命令 (scripts)

scripts 字段定义了快捷命令,简化复杂的终端操作。

修改 package.json 中的 scripts 部分:

{
  "scripts": {
    "build": "tsc",
    "start": "node dist/index.js",
    "dev": "ts-node src/index.ts"
  }
}

运行 编译命令时,只需 输入

npm run build

2. 配置 tsconfig.json:控制编译行为

tsconfig.json 是 TypeScript 编译器的指南针,告诉它如何将 .ts 代码转换为 .js 代码。

运行 以下命令生成基础配置文件:

npx tsc --init

打开 tsconfig.json调整 以下关键配置项以适应现代开发需求。

2.1 编译选项

以下选项决定了编译产物的规范和严格程度。

选项名 推荐值 作用说明
target "ES2020" 指定编译后的 JavaScript 版本。
module "commonjs" 指定模块系统(Node.js 常用 commonjs,前端常用 ESNext)。
outDir "./dist" 指定编译结果的输出目录。
rootDir "./src" 指定源代码(TypeScript)的根目录。
strict true 开启所有严格类型检查选项,强烈建议开启。
esModuleInterop true 允许使用 import 语法导入 CommonJS 模块。

配置 示例如下:

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "commonjs",
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules"]
}

2.2 文件包含与排除

明确告诉编译器哪些文件需要处理,哪些需要忽略。

设置 include 字段,指定 需要编译的文件路径:

"include": ["src/**/*"]

设置 exclude 字段,排除 不需要编译的目录:

"exclude": ["node_modules", "dist"]

3. 协同工作:构建完整流程

将两个文件结合使用,即可实现从编写代码到打包运行的全自动化流程。当你在终端 执行 npm run build 时,系统会按照既定逻辑运行。

以下是该过程的执行逻辑流:

graph LR A[开发者] -- "执行: npm run build" --> B["package.json"] B -- "读取: scripts.build" --> C["tsc 编译器"] C -- "读取配置" --> D["tsconfig.json"] D -- "返回规则: target, outDir" --> C C -- "扫描: src 目录" --> E[".ts 源文件"] E -- "编译输出" --> F["dist 目录 .js 文件"]

为了确保上述流程顺畅,请按以下步骤 检查 项目结构:

  1. 创建 src 目录,并在其中 编写 index.ts 文件。
  2. 确认 tsconfig.json 中的 rootDir 指向 src
  3. 确认 tsconfig.json 中的 outDir 指向 dist
  4. package.json添加 "build": "tsc"
  5. 运行 npm run build
  6. 查看 dist 目录是否生成了对应的 .js 文件。

评论 (0)

暂无评论,快来抢沙发吧!

扫一扫,手机查看

扫描上方二维码,在手机上查看本文