TypeScript安装与配置 #
一、安装TypeScript #
1.1 使用npm安装 #
最常见的方式是通过npm(Node.js包管理器)安装TypeScript:
npm install -g typescript
安装完成后,可以验证安装:
tsc --version
输出类似:
Version 5.4.2
1.2 使用yarn安装 #
如果你使用yarn作为包管理器:
yarn global add typescript
1.3 使用pnpm安装 #
如果你使用pnpm:
pnpm add -g typescript
1.4 本地安装(推荐) #
在项目中本地安装TypeScript:
npm install typescript --save-dev
或:
yarn add typescript --dev
本地安装后,可以通过npx运行:
npx tsc --version
1.5 使用安装包安装 #
从TypeScript官网下载安装包进行安装。
二、TypeScript编译器(tsc) #
2.1 编译单个文件 #
创建一个简单的TypeScript文件hello.ts:
const message: string = 'Hello, TypeScript!';
console.log(message);
使用tsc编译:
tsc hello.ts
这将生成hello.js文件。
2.2 监听模式 #
使用--watch或-w参数监听文件变化:
tsc hello.ts --watch
2.3 常用编译选项 #
| 选项 | 说明 |
|---|---|
--outDir |
指定输出目录 |
--target |
指定ECMAScript目标版本 |
--module |
指定模块系统 |
--strict |
启用所有严格类型检查选项 |
--watch |
监听文件变化 |
--help |
显示帮助信息 |
tsc hello.ts --outDir dist --target ES2020 --strict
三、tsconfig.json配置文件 #
3.1 创建配置文件 #
使用tsc --init创建默认配置文件:
tsc --init
这将生成tsconfig.json文件。
3.2 基本配置结构 #
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
3.3 常用配置选项详解 #
target #
指定编译后的JavaScript版本:
{
"compilerOptions": {
"target": "ES2020"
}
}
可选值:ES3、ES5、ES6/ES2015、ES2016…ES2022、ESNext
module #
指定模块系统:
{
"compilerOptions": {
"module": "commonjs"
}
}
可选值:commonjs、amd、system、umd、es6/ES2015、ES2020、ESNext、None
outDir和rootDir #
{
"compilerOptions": {
"outDir": "./dist",
"rootDir": "./src"
}
}
outDir:编译输出目录rootDir:源代码根目录
strict #
启用所有严格类型检查选项:
{
"compilerOptions": {
"strict": true
}
}
等同于启用以下所有选项:
--strictNullChecks--strictFunctionTypes--strictBindCallApply--strictPropertyInitialization--noImplicitThis--alwaysStrict
esModuleInterop #
启用ES模块互操作性:
{
"compilerOptions": {
"esModuleInterop": true
}
}
允许使用CommonJS模块的默认导入:
import React from 'react';
sourceMap #
生成Source Map文件:
{
"compilerOptions": {
"sourceMap": true
}
}
lib #
指定编译时包含的库文件:
{
"compilerOptions": {
"lib": ["ES2020", "DOM"]
}
}
moduleResolution #
指定模块解析策略:
{
"compilerOptions": {
"moduleResolution": "node"
}
}
可选值:node(Node.js风格)、classic(TypeScript经典风格)
baseUrl和paths #
配置路径别名:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["src/*"],
"@components/*": ["src/components/*"]
}
}
}
使用:
import { Button } from '@components/Button';
3.4 include和exclude #
{
"include": [
"src/**/*",
"tests/**/*"
],
"exclude": [
"node_modules",
"dist",
"**/*.test.ts"
]
}
四、开发环境配置 #
4.1 VSCode配置 #
VSCode内置TypeScript支持,推荐安装以下扩展:
- TypeScript Importer:自动导入
- Move TS:移动文件时自动更新导入路径
工作区设置 #
创建.vscode/settings.json:
{
"typescript.tsdk": "node_modules/typescript/lib",
"typescript.enablePromptUseWorkspaceTsdk": true,
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
}
}
4.2 配置ESLint #
安装依赖:
npm install --save-dev eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin
创建.eslintrc.js:
module.exports = {
root: true,
parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint'],
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended'
],
rules: {
'@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
'@typescript-eslint/explicit-function-return-type': 'off'
}
};
4.3 配置Prettier #
安装依赖:
npm install --save-dev prettier
创建.prettierrc:
{
"semi": true,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "es5",
"printWidth": 100
}
五、项目结构示例 #
5.1 基本项目结构 #
my-typescript-project/
├── src/
│ ├── index.ts
│ ├── utils/
│ │ └── helpers.ts
│ └── types/
│ └── index.ts
├── dist/
├── node_modules/
├── package.json
├── tsconfig.json
├── .eslintrc.js
├── .prettierrc
└── .gitignore
5.2 package.json配置 #
{
"name": "my-typescript-project",
"version": "1.0.0",
"scripts": {
"build": "tsc",
"start": "node dist/index.js",
"dev": "tsc --watch",
"lint": "eslint src/**/*.ts",
"format": "prettier --write src/**/*.ts"
},
"devDependencies": {
"typescript": "^5.4.2",
"@typescript-eslint/parser": "^7.0.0",
"@typescript-eslint/eslint-plugin": "^7.0.0",
"eslint": "^8.57.0",
"prettier": "^3.2.0"
}
}
六、编译和运行 #
6.1 编译项目 #
npm run build
或直接运行:
tsc
6.2 运行编译后的代码 #
node dist/index.js
6.3 使用ts-node直接运行 #
安装ts-node:
npm install --save-dev ts-node
直接运行TypeScript:
npx ts-node src/index.ts
6.4 使用tsx运行 #
tsx是更快的TypeScript运行器:
npm install --save-dev tsx
运行:
npx tsx src/index.ts
七、常见问题 #
7.1 找不到模块 #
确保安装了类型定义:
npm install --save-dev @types/node
7.2 类型定义缺失 #
对于没有类型定义的库,可以:
- 安装
@types/包名 - 创建自定义声明文件
declare module 'some-library' {
export function someFunction(arg: string): number;
}
7.3 编译速度慢 #
使用增量编译:
{
"compilerOptions": {
"incremental": true
}
}
八、总结 #
本章介绍了TypeScript的安装和配置:
- 安装方式:npm、yarn、pnpm全局或本地安装
- 编译器使用:tsc命令和常用选项
- 配置文件:tsconfig.json详解
- 开发环境:VSCode、ESLint、Prettier配置
- 项目结构:推荐的项目组织方式
- 编译运行:多种运行TypeScript的方式
准备好开始编写第一个TypeScript程序了吗?让我们进入下一章。