TypeScript 简介与项目中配置
一、简介
TypeScript是⼀个开源的编程语⾔,通过在JavaScript的基础上添加静态类型定义构建⽽成。通过TypeScript编译器或Babel转译为JavaScript代码,可运⾏在任何浏览器,任何操作系统。
中文文档地址:https://www.tslang.cn/index.html
二、全局安装
安装命令
npm install -g typescript
# 检查安装是否成功
tsc --version
新建一个ts文件,例如index.ts
,在文件中输入以下代码:
let str: string = 'Hello Word!';
console.log(str);
打开终端输入tsc,就自动编译出对应的index.js文件。输入node index.js完成终端编译js代码,打印输出Hello Word!;
三、项目中配置
新建一个项目,在项目中使用TypeScript,需要进行以下配置:
# 初始化项目
npm init -y
# 安装typescript
npm install --save-dev typescript
# 安装ts-node
npm install --save-dev ts-node
# 生成配置文件tsconfig.json
tsc --init
四、项目中tsconfig.json配置说明
TypeScript 的 tsconfig.json 文件是 TypeScript 项目的核心配置文件,它定义了编译器选项和项目设置。
4.1 基本配置选项
{// 核心编译器选项"compilerOptions": {},// 明确包含的文件列表"files": [],// 包含的文件模式"include": ["src/**/*"],// 排除的文件模式"exclude": ["node_modules","**/*.spec.ts"],// 继承的配置文件"extends": [],// 项目引用"references": []
}
4.2 核心配置选项详解
{"compilerOptions": {"target": "ES2020", // 编译目标 JavaScript 版本"module": "ESNext", // 模块系统"lib": ["ES2020", "DOM"], // 包含的库文件定义"moduleResolution": "node", // 模块解析策略"allowSyntheticDefaultImports": true // 允许默认导入}
}
常用值:
target
:ES3
,ES5
,ES6
/ES2015
,ES2020
,ESNext
等module
:CommonJS
,AMD
,System
,UMD
,ES6
,ES2015
,ESNext
等lib
:ES5
,ES6
,ES2015
,DOM
,DOM.Iterable
,WebWorker
等
4.3 严格模式检查
{"compilerOptions": {"strict": true, // 启用所有严格类型检查"noImplicitAny": true, // 禁止隐式 any 类型"strictNullChecks": true, // 严格的 null 检查"strictFunctionTypes": true, // 严格的函数类型检查"strictBindCallApply": true, // 严格的 bind/call/apply 检查"strictPropertyInitialization": true,// 严格的属性初始化检查"noImplicitThis": true, // 禁止隐式 this"alwaysStrict": true // 始终以严格模式解析}
}
4.4 输出控制
{"compilerOptions": {"outDir": "./dist", // 输出目录"rootDir": "./src", // 根目录"outFile": "./bundle.js", // 将输出合并为单个文件"removeComments": true, // 删除注释"noEmit": false, // 不输出文件"declaration": true, // 生成 .d.ts 声明文件"declarationMap": true, // 生成声明文件的 sourcemap"sourceMap": true, // 生成 sourcemap 文件"inlineSourceMap": true, // 内联 sourcemap"inlineSources": true // 将源码包含在 sourcemap 中}
}
4.5 路径映射与模块解析
{"compilerOptions": {"baseUrl": "./", // 解析非相对模块的基础目录"paths": { // 模块名到基于 baseUrl 的路径映射"@/*": ["src/*"],"components/*": ["src/components/*"],"utils/*": ["src/utils/*"]},"rootDirs": [ // 多个根目录"src","generated"],"typeRoots": [ // 类型定义根目录"./node_modules/@types","./src/types"],"types": ["node", "jest"] // 包含的类型包}
}
4.6 实验性与高级选项
{"compilerOptions": {"experimentalDecorators": true, // 启用实验性装饰器"emitDecoratorMetadata": true, // 为装饰器生成元数据"jsx": "react-jsx", // JSX 代码生成"jsxFactory": "React.createElement", // JSX 工厂函数"jsxFragmentFactory": "React.Fragment", // JSX Fragment 工厂"useDefineForClassFields": true, // 使用 define 定义类字段"useUnknownInCatchVariables": true // catch 变量为 unknown 类型}
}
4.7 其他常用选项
{"compilerOptions": {"noFallthroughCasesInSwitch": true, // 禁止 switch 语句中的贯穿情况"noUnusedLocals": true, // 报告未使用的局部变量"noUnusedParameters": true, // 报告未使用的参数"noImplicitReturns": true, // 禁止函数没有返回值时的隐式 any 类型"noUncheckedIndexedAccess": true, // 报告索引访问时的未检查类型"noPropertyAccessFromIndexSignature": true // 禁止通过索引签名访问属性}
}
4.8 项目的包含与排除
{"include": ["src/**/*", // src 目录下的所有文件"tests/**/*", // tests 目录下的所有文件"**/*.ts", // 所有 .ts 文件"**/*.tsx" // 所有 .tsx 文件],"exclude": ["node_modules", // 排除 node_modules"**/*.test.ts", // 排除测试文件"**/*.spec.ts", // 排除测试文件"dist", // 排除输出目录"build" // 排除构建目录],"files": [ // 明确包含的特定文件"src/main.ts","src/core/index.ts"]
}
五、常用配置预设
5.1 Node.js 项目配置
{"compilerOptions": {"target": "ES2020","module": "CommonJS","lib": ["ES2020"],"outDir": "./dist","rootDir": "./src","strict": true,"esModuleInterop": true,"skipLibCheck": true,"forceConsistentCasingInFileNames": true,"resolveJsonModule": true},"include": ["src/**/*"],"exclude": ["node_modules", "dist"]
}
5.2 React 项目配置
{"compilerOptions": {"target": "ES2020","module": "ESNext","lib": ["ES2020", "DOM"],"outDir": "./dist","rootDir": "./src","strict": true,"esModuleInterop": true,"skipLibCheck": true,"forceConsistentCasingInFileNames": true,"resolveJsonModule": true,"jsx": "react-jsx"},"include": ["src/**/*"],"exclude": ["node_modules", "dist"]
}
5.3 工具库项目配置
{"compilerOptions": {"target": "ES2019","module": "ESNext","lib": ["ES2020", "DOM"],"declaration": true,"declarationMap": true,"sourceMap": true,"outDir": "./dist","rootDir": "./src","strict": true,"esModuleInterop": true,"skipLibCheck": true,"forceConsistentCasingInFileNames": true},"include": ["src/**/*"],"exclude": ["node_modules", "dist", "**/*.test.ts", "**/*.spec.ts"]
}
5.4 Monorepo项目引用
{"references": [{ "path": "./packages/core" }, // 引用子项目{ "path": "./packages/utils" },{ "path": "./packages/ui" }],"compilerOptions": {"composite": true, // 启用项目引用"incremental": true, // 启用增量编译"tsBuildInfoFile": "./buildcache" // 增量编译信息文件位置}
}