前端 ts 配置

ts 为什么需要配置?

因为 ts 需要编译。

ts 源文件 -> ts 编译器(package.json 依赖包里面就有) -> js 代码

 "devDependencies": {
  ...
 "typescript": "~5.7.2",
  ...
  }
# TypeScript 编译选项完整指南

本文档详细说明 TypeScript (`tsconfig.json`) 中所有核心编译选项的配置方法。

## 快速开始
生成默认 `tsconfig.json`:
```bash
tsc --init

核心配置选项

基础配置

选项 类型 默认值 描述
target string ES3 编译目标 ECMAScript 版本 (e.g. ES5, ES2015, ES2022)
module string CommonJS 模块系统 (CommonJS, ES2015, ESNext, Node16 等)
outDir string - 输出目录 (默认同源文件目录)
rootDir string - 源文件根目录
baseUrl string - 模块解析基础路径

严格检查

选项 类型 默认 描述
strict boolean true 启用所有严格类型检查
noImplicitAny boolean true* 禁止隐式 any 类型
strictNullChecks boolean true* 严格的 null/undefined 检查
strictFunctionTypes boolean true* 严格的函数类型检查

模块解析

选项 类型 描述
moduleResolution string node/classic/bundler
paths object 模块路径映射 (需配合 baseUrl)
```json
“paths”: {
“@utils/*”: [“src/utils/*”]
}
```

类型定义

选项 类型 描述
types string[] 包含的类型声明包
typeRoots string[] 类型声明文件查找路径

输出控制

选项 类型 描述
sourceMap boolean 生成 source map 文件
inlineSourceMap boolean 内联 source map
declaration boolean 生成 .d.ts 声明文件

高级配置

选项 类型 描述
allowJs boolean 允许编译 JS 文件
checkJs boolean 对 JS 文件进行类型检查
jsx string JSX 处理方式 (preserve/react-native/react)
experimentalDecorators boolean 启用装饰器语法

完整配置示例

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "NodeNext",
    "outDir": "./dist",
    "rootDir": "./src",

    "strict": true,
    "noImplicitAny": true,

    "moduleResolution": "NodeNext",
    "baseUrl": ".",
    "paths": {
      "@utils/*": ["src/utils/*"]
    },

    "sourceMap": true,
    "declaration": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules"]
}

常用场景配置

Node.js 项目

{
  "target": "ES2022",
  "module": "NodeNext",
  "moduleResolution": "NodeNext"
}

浏览器项目

{
  "target": "ES6",
  "lib": ["ES6", "DOM"],
  "module": "ES6"
}

注意事项

  1. strict 启用时会自动开启所有严格检查选项
  2. moduleResolution 默认根据 module 设置自动选择
  3. 使用 paths 时必须设置 baseUrl
  4. TypeScript 5.0+ 推荐使用 moduleResolution: "bundler" 配合现代打包工具

完整选项参考:官方编译选项文档
```

本作品采用《CC 协议》,转载必须注明作者和本文链接
九九一十八,一步一个脚印
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!