TypeScript 编译器提供了多种编译选项来控制编译过程和生成的 JavaScript 代码。这些选项可以通过命令行参数传递给 tsc 命令,或者在 tsconfig.json 文件中配置。以下是一些常用的 TypeScript 编译选项:
基本选项
-
--target/-t: 指定编译后的 JavaScript 版本。例如ES5,ES6/ES2015,ES2016,ES2017,ES2018,ES2019,ES2020,ESNext等。{ "compilerOptions": { "target": "ES6" } } -
--module/-m: 指定要使用的模块系统。例如commonjs,amd,umd,system,es6/es2015,esnext等。{ "compilerOptions": { "module": "commonjs" } } -
--lib: 指定要包含在编译中的库文件。例如ES6,DOM,ES2015.Collection等。{ "compilerOptions": { "lib": ["ES6", "DOM"] } } -
--outDir: 指定输出目录。{ "compilerOptions": { "outDir": "./dist" } } -
--rootDir: 用于指定输入文件的根目录。{ "compilerOptions": { "rootDir": "./src" } } -
--sourceMap: 生成对应的.map文件。{ "compilerOptions": { "sourceMap": true } }
严格类型检查选项
-
--strict: 启用所有严格类型检查选项。{ "compilerOptions": { "strict": true } } -
--noImplicitAny: 不允许隐式的any类型。{ "compilerOptions": { "noImplicitAny": true } } -
--strictNullChecks: 启用严格的null和undefined检查。{ "compilerOptions": { "strictNullChecks": true } } -
--strictFunctionTypes: 启用函数类型的严格检查。{ "compilerOptions": { "strictFunctionTypes": true } } -
--strictPropertyInitialization: 启用类属性初始化的严格检查。{ "compilerOptions": { "strictPropertyInitialization": true } }
模块解析选项
-
--baseUrl: 基础目录,用于解析非相对模块名。{ "compilerOptions": { "baseUrl": "./" } } -
--paths: 模块名到基于baseUrl的路径映射。{ "compilerOptions": { "baseUrl": "./", "paths": { "utils/*": ["src/utils/*"] } } } -
--rootDirs: 一个根文件夹列表,它们结合在一起表示项目运行时的结构。{ "compilerOptions": { "rootDirs": ["src", "generated"] } }
高级选项
-
--noEmit: 不生成输出文件,只进行类型检查。{ "compilerOptions": { "noEmit": true } } -
--declaration: 生成相应的.d.ts文件。{ "compilerOptions": { "declaration": true } } -
--incremental: 增量编译以加快后续的编译速度。{ "compilerOptions": { "incremental": true } } -
--skipLibCheck: 跳过所有的声明文件的类型检查。{ "compilerOptions": { "skipLibCheck": true } } -
--emitDecoratorMetadata: 为装饰器生成元数据。{ "compilerOptions": { "emitDecoratorMetadata": true } }
示例 tsconfig.json
{
"compilerOptions": {
"target": "ES6",
"module": "commonjs",
"lib": ["ES6", "DOM"],
"outDir": "./dist",
"rootDir": "./src",
"sourceMap": true,
"strict": true,
"baseUrl": "./",
"paths": {
"utils/*": ["src/utils/*"]
},
"incremental": true,
"skipLibCheck": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "**/*.spec.ts"]
}
这些编译选项帮助你定制 TypeScript 编译器的行为,以适应项目的具体需求。可以根据具体项目的需要组合使用这些选项。