TypeScript 学习项目创建_1

TypeScript 学习项目创建_1

创建项目

  1. 初始化项目npm init -y

  2. 项目内安装 TypeScript
    npm i typescript --save-dev

    全局安装(可选)
    npm install -g typescript

    卸载全局的 TypeScript(可选)
    npm uninstall -g typescript

    全局安装验证
    tes -v 会输出版本

  3. 创建 TypeScript 配置文件
    npx tsc --init

粘贴以下内容

json 复制代码
{
  "compilerOptions": {
    "target": "es6",                      // 编译目标版本
    "module": "commonjs",                  // 模块系统
    "lib": ["es6"],                        // 包含的库文件
    "outDir": "./dist",                    // 输出目录
    "rootDir": "./src",                    // 源代码目录
    "strict": true,                       // 启用严格模式
    "esModuleInterop": true,              // 兼容 ES 模块
    "skipLibCheck": true,                 // 跳过库文件检查
    "noEmitOnError": true                 // 错误时不生成 JS
  },
  "include": ["src/**/*"],                // 包含的文件
  "exclude": ["node_modules"]             // 排除的文件
}

安装其他包(express)

  1. 安装 Express
    npm install express

  2. 安装开发依赖,需要执行使用typescript的,默认是JavaScript的。
    npm install --save-dev typescript @types/node @types/express ts-node nodemon

  3. 包配置文件 (package.json)

json 复制代码
{
  "name": "learn_1",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "dev": "ts-node src/app.ts",         // 开发模式
    "build": "tsc",                      // 编译 TypeScript
    "start": "node dist/app.js"          // 生产模式
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": "",
  "dependencies": {
    "express": "^5.2.1"                  // 运行时依赖
  },
  "devDependencies": {
    "@types/express": "^5.0.6",          // Express 类型声明
    "@types/node": "^25.0.3",            // Node.js 类型声明
    "ts-node": "^10.9.2",                // 直接运行 TypeScript
    "typescript": "^5.9.3"               // TypeScript 编译器
  }
}

Express 简单服务器实现

typescript 复制代码
// src/app.ts
import express, { Request, Response } from 'express'; //导入express模块

const app = express();
const port: number = 3000;
const host: string = "0.0.0.0";

// 根路由
app.get('/', (req: Request, res: Response) => {
    res.send('Hello World');
});

// 启动服务器
app.listen(port, host, () => {
    console.log(`Server is running at http://${host}:${port}`);
});

编译与监控命令

监控文件变化并实时编译
tsc --watch

编译选项说明:
"noEmitOnError": true

当值为 false 时:即使有类型错误也会生成 JS 文件

当值为 true 时:发现类型错误时不生成 JS 文件

代码注释规范

默认注释

使用/** 按下Enter 自动补充注释

typescript 复制代码
/**
 * 
 * @param age 
 * @returns 
 */
function SayHello(age: number): string {
    return `Hello! You are ${age} years old.`;
}

使用 VS Code 扩展 Document This

使用/** ,然后选择Document This 按下Enter 自动补充注释,带有参数类型和返回值类型

typescript 复制代码
/**
 * 问好函数
 * @description 
 * @param {number} age - 
 * @return {*}  {string} 
 */
function SayHello(age: number): string {
    return `Hello! You are ${age} years old.`;
}

第三方包安装

先直接安装然后使用,如果不报错就继续用,如果报错就添加@type 或者两个都安装

powershell 复制代码
# 不确定时,先安装包
npm install some-package

# 如果 TypeScript 报错,再安装类型声明
npm install --save-dev @types/some-package

# 或者一次性安装(如果存在类型声明)
npm install some-package @types/some-package

项目运行

开发环境

使用 npm run dev 通过 ts-node 直接运行 TypeScript

但是运行一次就退出了。

生产环境

先运行 npm run build编译,然后使用 npm start 运行

常用目录结构

text 复制代码
typescript-learn/
├── src/                    # 源代码目录
│   ├── app.ts             # 应用入口文件
│   ├── routes/            # 路由定义
│   │   └── index.ts       # 主路由
│   ├── controllers/       # 控制器
│   │   └── home.controller.ts
│   ├── services/          # 业务逻辑
│   ├── models/            # 数据模型
│   ├── middleware/        # 中间件
│   ├── utils/           # 工具函数
│   ├── types/            # TypeScript 类型定义
│   │   └── global.d.ts   # 全局类型声明
│   └── config/           # 配置文件
│       └── constants.ts  # 常量文件
├── dist/                  # 编译输出目录
├── .gitignore            # Git 忽略文件
├── tsconfig.json         # TypeScript 配置
├── package.json          # 项目配置
└── README.md             # 项目说明
相关推荐
xkxnq7 小时前
第一阶段:Vue 基础入门(第 7 天)
前端·javascript·vue.js
光头闪亮亮7 小时前
企业协同办公系统(OA)-【图标选择器】模块开发详解
前端·javascript·vue.js
pas1367 小时前
22-mini-vue props
前端·javascript·vue.js
pas1367 小时前
23-mini-vue 实现 emit 功能
前端·javascript·vue.js
cute_ming7 小时前
从 Node.js + TypeScript 无缝切换到 Python 的最佳实践
python·typescript·node.js
黛色正浓7 小时前
leetCode-热题100-子串合集(JavaScript)
javascript·算法·leetcode
程序员Agions7 小时前
React 自定义 Hooks 生存指南:7 个让你少加班的"偷懒"神器
前端·javascript
爱学习的小康7 小时前
js 文件读取 修改 创建
前端·javascript·vue.js
菜的不敢吱声7 小时前
swift学习第2,3天
python·学习·swift
Sailing8 小时前
AI 流式对话该怎么做?SSE、fetch、axios 一次讲清楚
前端·javascript·面试