React中的TypeScript配置文件:tsconfig.json各配置项详细说明
TS配置文件 tsconfig.json
tsconfig.js指定:项目文件和项目编译所需的配置项。
注意:TS的配置项非常多(100+),以 CRA(React脚手架工具 create-react-app(简称:CRA)) 项目中的配置为例来学习,其他的配置项用到时查文档typescriptlang.org/tsconfig#include
即可。
- tsconfig.json 文件所在目录为项目根目录(与 package.json 同级)。
- tsconfig.json 可以自动生成,命令:
tsc --init
。
// 这是 tsconfig.json 配置文件// 说明:所有的配置项都可以通过鼠标移入的方式,来查看配置项的解释说明// tsconfig 文档链接(https://www.typescriptlang.org/tsconfig){ "compilerOptions": { // 编译选项 "target": "es5", // 生成代码的语言版本 "lib": [ "dom", "dom.iterable", "esnext" ], // 指定要包含在编译中的library "allowJs": true, // 允许 ts 编译器编译 js 文件 "skipLibCheck": true, // 跳过声明文件的类型检查 "esModuleInterop": true, // es 模块互操作,屏蔽 ESModule和CommonJS之间的差异 "allowSyntheticDefaultImports": true,// 允许通过import x from 'y' 即使模块没有显式指定 default 导出 "strict": true, // 开启严格模式 "forceConsistentCasingInFileNames": true, // 对文件名称强制区分大小写 "noFallthroughCasesInSwitch": true, // 为 switch 语句启用错误报告 "module": "esnext", // 生成代码的模块化标准 "moduleResolution": "node", // 模块解析(查找)策略 "resolveJsonModule": true, // 允许导入扩展名为 .json 的模块 "isolatedModules": true,// 是否将没有 import/export 的文件视为旧(全局而非模块化)脚本文件。 "noEmit": true, // 编译时不生成任何文件(只进行类型检查) "jsx": "react-jsx" // 指定将 JSX 编译成什么形式 }, "include": ["src"] // 指定允许 ts 处理的目录}
除了在 tsconfig.json 文件中使用编译配置外,还可以通过命令行来使用。
使用演示:tsc hello.ts --target es6
。指定编译生成 es6 版本的js文件。
注意:
- tsc 后带有输入文件时(比如,tsc hello.ts),将忽略 tsconfig.json 文件。
- tsc 后不带输入文件时(比如,tsc),才会启用 tsconfig.json 。
推荐使用:tsconfig.json 配置文件。