设置开发环境
让我们为 TypeScript 开发准备好你的开发环境。
先决条件
在开始之前,确保你有:
- Node.js(版本 16 或更高) - 在此下载
- 代码编辑器(我们推荐 VS Code)
安装 TypeScript
你可以全局安装 TypeScript 或将其作为项目依赖安装。
全局安装
npm install -g typescript
验证安装:
tsc --version
项目本地安装(推荐)
mkdir my-ts-project
cd my-ts-project
npm init -y
npm install typescript --save-dev
创建你的第一个 TypeScript 文件
创建一个名为 hello.ts 的文件:
function sayHello(name: string): void {
console.log(`Hello, ${name}!`);
}
sayHello("TypeScript");
编译它:
npx tsc hello.ts
这会创建 hello.js:
function sayHello(name) {
console.log("Hello, ".concat(name, "!"));
}
sayHello("TypeScript");
运行它:
node hello.js
TypeScript 配置
对于实际项目,你需要一个 tsconfig.json 文件:
npx tsc --init
这会创建一个包含许多选项的配置文件。这里是一个最小设置:
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"strict": true,
"outDir": "./dist",
"rootDir": "./src"
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}
关键选项说明
| 选项 | 描述 |
|---|---|
target | 编译到的 JavaScript 版本 |
module | 模块系统(commonjs、ES 模块等) |
strict | 启用所有严格类型检查 |
outDir | 编译后的 JS 文件存放位置 |
rootDir | TS 源文件存放位置 |
VS Code 设置
VS Code 内置了出色的 TypeScript 支持。为了获得最佳体验:
- 安装 ESLint 扩展
- 安装 Prettier 扩展
- 在设置中启用”保存时格式化”
项目结构
典型的 TypeScript 项目结构:
my-project/
├── src/
│ ├── index.ts
│ └── utils.ts
├── dist/ # 编译后的 JS(自动生成)
├── node_modules/
├── package.json
└── tsconfig.json
你现在可以编写 TypeScript 了!下一章,我们将探索 TypeScript 的类型系统。