TypeScript 安装与配置
TypeScript 的安装与配置是开发的第一步,下面梳理核心步骤。
TypeScript 安装
npm 全局安装
Bash
npm install -g typescript
安装完成后验证:
Bash
tsc --version
# 输出示例:Version 5.4.5
项目本地安装
Bash
npm init -y
npm install typescript --save-dev
本地安装后通过 npx 调用:
Bash
npx tsc --version
版本管理
指定版本安装:
Bash
npm install -g typescript@5.3.3
tsconfig.json 配置
初始化配置
Bash
tsc --init
生成默认配置文件:
JSON
{
"compilerOptions": {
"target": "ES2016",
"module": "commonjs",
"strict": true,
"outDir": "./dist",
"rootDir": "./src",
"esModuleInterop": true
}
}
核心编译选项
| 选项 | 说明 | 常用值 |
|---|---|---|
target | 编译目标 JavaScript 版本 | ES5/ES2015/ES2020/ESNext |
module | 模块系统类型 | commonjs/es2015/esnext/node16 |
outDir | 输出目录 | ./dist/./build |
rootDir | 源码根目录 | ./src |
strict | 启用所有严格类型检查选项 | true/false |
esModuleInterop | 兼容 CommonJS 模块导入 | true/false |
常用配置示例
JSON
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"moduleResolution": "bundler",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist", "**/*.test.ts"]
}
注意:
skipLibCheck跳过声明文件类型检查,可显著提升编译速度;declaration生成.d.ts文件供其他项目使用。
编译命令
Bash
# 编译整个项目
tsc
# 监听模式(文件变化时自动编译)
tsc --watch
# 指定配置文件
tsc --project tsconfig.prod.json
要点总结
- 全局安装
typescript提供tsc命令,本地安装作为项目依赖更可控 tsconfig.json中target决定输出 JS 版本,module决定模块系统strict: true启用严格模式,推荐生产项目开启outDir和rootDir分离源码与编译产物,保持项目结构清晰
📝 发现内容有误?点击此处直接编辑