5分钟搭建你的第一个TypeScript项目

在上一篇文章中,我们深入探讨了TypeScript的核心价值。现在,是时候动手实践了!很多初学者在面对新工具时会有"配置恐惧症",但请相信我,搭建TypeScript开发环境比你想的要简单得多。

本文将用最清晰的步骤,带你在5分钟内完成TypeScript环境的搭建、配置,并运行你的第一个TypeScript程序。

准备工作:确保Node.js环境

TypeScript需要Node.js环境来运行其编译器。如果你还没有安装:

  1. 下载Node.js :访问 Node.js官网 下载LTS(长期支持)版本

  2. 验证安装 :打开终端/命令提示符,运行:

    bash 复制代码
    node --version
    npm --version

    如果两个命令都返回版本号,说明安装成功。

第一步:创建项目并初始化

打开终端,依次执行以下命令:

bash 复制代码
# 1. 创建项目目录
mkdir my-first-typescript-project
cd my-first-typescript-project

# 2. 初始化npm项目(生成package.json)
npm init -y

# 3. 安装TypeScript编译器
npm install typescript --save-dev

# 4. 安装类型声明文件(用于Node.js环境)
npm install @types/node --save-dev

关键说明:

  • --save-dev 表示这些是开发依赖,不会包含在最终的生产代码中
  • @types/node 为Node.js API提供了TypeScript类型定义

第二步:创建TypeScript配置文件

TypeScript的强大之处在于其可配置性。创建配置文件 tsconfig.json:

bash 复制代码
# 生成默认配置文件
npx tsc --init

现在打开生成的 tsconfig.json 文件,我们进行一些关键配置:

json 复制代码
{
  "compilerOptions": {
    /* 语言和环境 */
    "target": "ES2020",                // 编译目标ES版本
    "lib": ["ES2020", "DOM"],          // 包含的库文件(DOM用于浏览器环境)
    
    /* 模块系统 */
    "module": "commonjs",              // 模块规范
    "rootDir": "./src",                // 源代码目录
    "outDir": "./dist",                // 输出目录
    
    /* 类型检查严格性(推荐开启) */
    "strict": true,                    // 开启所有严格类型检查
    "noImplicitAny": true,             // 禁止隐式any类型
    
    /* 额外的检查 */
    "noUnusedLocals": true,            // 报告未使用的局部变量
    "noUnusedParameters": true,        // 报告未使用的参数
    
    /* 模块解析 */
    "esModuleInterop": true,           // 兼容CommonJS和ES模块
    "skipLibCheck": true,              // 跳过库文件类型检查以提升性能
    
    /* 实验性功能(根据需求开启) */
    "experimentalDecorators": true,    // 启用装饰器
    "emitDecoratorMetadata": true      // 为装饰器生成元数据
  },
  "include": ["src/**/*"],             // 包含src目录下所有文件
  "exclude": ["node_modules", "dist"]  // 排除目录
}

配置要点解析:

  • target: 指定编译后的JavaScript版本,现代项目推荐ES2020
  • strict: true: 强烈建议开启,这是TypeScript价值的核心体现
  • rootDir/outDir: 保持源代码和编译结果的分离,项目结构更清晰

第三步:创建项目结构

创建以下目录结构:

perl 复制代码
my-first-typescript-project/
├── src/           # TypeScript源代码
├── dist/          # 编译后的JavaScript代码
├── node_modules/
├── package.json
└── tsconfig.json

在 src 目录中创建你的第一个TypeScript文件:

src/greeter.ts

typescript 复制代码
// 定义一个接口 - 这是TypeScript的核心特性
interface Person {
  firstName: string;
  lastName: string;
  age?: number; // 可选属性
}

// 使用接口作为类型注解
class Student implements Person {
  constructor(
    public firstName: string, 
    public lastName: string, 
    public age?: number
  ) {}
  
  // 类型注解的返回值
  getFullName(): string {
    return `${this.firstName} ${this.lastName}`;
  }
}

// 强类型函数参数和返回值
function greeter(person: Person): string {
  return `Hello, ${person.firstName} ${person.lastName}`;
}

// 使用我们的类和函数
const user = new Student("Jane", "Doe", 23);

// 这里你会体验到TypeScript的智能提示!
// 尝试输入 `user.` 看看IDE会提示什么
console.log(user.getFullName());
console.log(greeter(user));

// 体验类型安全:取消下面注释看看会发生什么
// const wrongUser = { firstNam: "John", lastName: "Smith" };
// console.log(greeter(wrongUser)); // ❌ 编译错误!

src/main.ts

typescript 复制代码
// 简单的启动文件
import { greeter, Student } from './greeter';

const students = [
  new Student("Alice", "Johnson", 20),
  new Student("Bob", "Smith", 22),
  new Student("Charlie", "Brown") // age是可选的
];

students.forEach(student => {
  console.log(greeter(student));
});

console.log(`Total students: ${students.length}`);

第四步:配置构建脚本

修改 package.json,添加有用的npm脚本:

json 复制代码
{
  "name": "my-first-typescript-project",
  "version": "1.0.0",
  "scripts": {
    "build": "tsc",
    "build:watch": "tsc --watch",
    "start": "node dist/main.js",
    "dev": "tsc && node dist/main.js"
  },
  "devDependencies": {
    "typescript": "^5.0.0",
    "@types/node": "^20.0.0"
  }
}

现在你可以使用这些命令:

bash 复制代码
npm run build    # 一次性编译
npm run dev      # 编译并运行
npm run build:watch # 监听文件变化自动重新编译

第五步:运行你的程序

bash 复制代码
# 编译TypeScript到JavaScript
npm run build

# 运行编译后的程序
npm start

如果一切顺利,你将在终端看到:

yaml 复制代码
Hello, Alice Johnson
Hello, Bob Smith  
Hello, Charlie Brown
Total students: 3

进阶:配置开发环境

1. 安装VS Code扩展

在VS Code中安装以下扩展提升开发体验:

  • TypeScript Importer - 自动管理import语句
  • Error Lens - 内联显示错误信息
  • Bracket Pair Colorizer - 彩色括号匹配

2. 调试配置

创建 .vscode/launch.json 来启用调试:

json 复制代码
{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Debug TypeScript",
      "program": "${workspaceFolder}/dist/main.js",
      "preLaunchTask": "npm: build",
      "outFiles": ["${workspaceFolder}/dist/**/*.js"]
    }
  ]
}

遇到问题?常见解决方案

问题1 : Cannot find module 错误

  • 解决 : 确保在导入时使用正确的相对路径,如 './greeter'

问题2: 编译后运行显示乱码(Windows)

  • 解决 : 在终端中执行 chcp 65001 切换为UTF-8编码

问题3: 修改代码后需要手动重新编译

  • 解决 : 使用 npm run build:watch 开启监听模式

理解编译过程

通过查看 dist 目录下的编译结果,你可以直观地看到TypeScript到JavaScript的转换:

dist/greeter.js (编译结果)

javascript 复制代码
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Student = void 0;
// 类定义被转换为ES5构造函数
class Student {
    constructor(firstName, lastName, age) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }
    // 方法被添加到原型上
    getFullName() {
        return `${this.firstName} ${this.lastName}`;
    }
}
exports.Student = Student;
// 接口在编译后被完全擦除,不会出现在JS中
function greeter(person) {
    return `Hello, ${person.firstName} ${person.lastName}`;
}
exports.greeter = greeter;
const user = new Student("Jane", "Doe", 23);
console.log(user.getFullName());
console.log(greeter(user));

注意:接口(interface Person)在编译后完全消失了,这证明了TypeScript的类型是开发时工具,不影响运行时性能。

总结

恭喜!你已经成功:

✅ 搭建了TypeScript开发环境

✅ 配置了专业的 tsconfig.json

✅ 编写了具有类型注解的TypeScript代码

✅ 理解了编译过程和工作原理

✅ 配置了实用的开发脚本

你现在拥有了一个完整的TypeScript项目模板,可以作为未来所有TypeScript项目的基础。

相关推荐
lovingsoft27 分钟前
Chrome Lighthouse 详解
前端·chrome
Qlly37 分钟前
全栈工程师怎么接需求?从一句「加个功能」聊到能开发、能验收
前端·后端
马可家的菠萝41 分钟前
你的微信“文件传输助手”,是不是已经成了第二个网盘?
前端·后端·架构
略略略啦41 分钟前
Vibe Coding 基于Spec DD和TDD的实践指南
前端
shmily麻瓜小菜鸡1 小时前
前端实现图片与PDF文字识别敏感信息打码方案
前端·pdf·状态模式
打工仔折腾 AI1 小时前
LangChain 工具调用实战:从 Tool 定义到 Agent 执行链路拆解
java·前端·人工智能·后端·python·langchain·ai agent 实战
汉堡大王95271 小时前
单次输出拉到100万Token:拆完 Gemini 4 Argon 的续写协议,才看懂谷歌这7个月在憋什么
前端·人工智能·后端
看浪的路人1 小时前
第9讲:大模型应用监控与可观测性——OpenTelemetry + Prometheus + Grafana 全链路追踪
java·前端·spring
内存过载1 小时前
用表格模拟甘特图:项目排期的土办法
前端·低代码
葡萄城技术团队2 小时前
用 SpreadJS 数据验证实现省市区三级联动
前端