express 项目支持 typescript 实战

首先创建一个express项目

  • 初始化项目
shell 复制代码
mkdir myapp
cd myapp
npm init (都用默认值)
  • 添加依赖包
shell 复制代码
npm install express nodemon
  • 修改 package.json
shell 复制代码
{
  "name": "myapp",
  "version": "1.0.0",
  "description": "",
  "main": "src/index.js",
  "scripts": {
    "start": "node src/index.js",
    "dev": "nodemon src/index.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.2",
    "nodemon": "^3.0.3"
  }
}
  • 修改工程脚本 src/index.js
shell 复制代码
const express = require('express');

const app = express();

const port = process.env.PORT || 3000;

app.get("/", (req, res, next) => {
  res.send("Express Server");
});

app.listen(port, () => {
  console.log(`[server]: Server is running at http://localhost:${port}`);
});

基于javascript的express创建好了,可以启动"npm run dev"验证一下。

express + typescript 改造

  • 添加typescript使用的包
shell 复制代码
npm install -D typescript @types/express @types/node

npm install -D ts-node
  • 生成 tsconfig.json
shell 复制代码
npx tsc --init

命令运行后,会生成 tsconfig.json 文件,我们添加一下 "outDir": "./dist", 修改后内容如下:

shell 复制代码
{
  "compilerOptions": {
    "target": "es2016",
    "module": "commonjs",
    "outDir": "./dist",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  }
}
  • 将 src/index.js 改名成 src/index.ts,内容改成typescript脚本
shell 复制代码
import express, { Express, Request, Response } from "express";

const app: Express = express();
const port = process.env.PORT || 3000;

app.get("/", (req: Request, res: Response) => {
  res.send("Express + TypeScript Server");
});

app.listen(port, () => {
  console.log(`[server]: Server is running at http://localhost:${port}`);
});
  • 修改 package.json 的 scripts,内容如下
shell 复制代码
{
  "name": "myapp",
  "version": "1.0.0",
  "description": "",
  "main": "dist/index.js",
  "scripts": {
    "build": "npx tsc",
    "start": "node dist/index.js",
    "dev": "nodemon src/index.ts"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.2",
    "nodemon": "^3.0.3"
  },
  "devDependencies": {
    "@types/express": "^4.17.21",
    "@types/node": "^20.11.5",
    "ts-node": "^10.9.2",
    "typescript": "^5.3.3"
  }
}

到这里,express + typescript 的工程改造就完成了,可以使用 "npm run dev" 命令启动工程进行测试。

相关推荐
bitbitDown32 分钟前
从零打造一个 Vite 脚手架工具:比你想象的简单多了
前端·javascript·面试
冴羽2 小时前
为什么在 JavaScript 中 NaN !== NaN?背后藏着 40 年的技术故事
前端·javascript·node.js
久爱@勿忘2 小时前
vue下载项目内静态文件
前端·javascript·vue.js
前端炒粉2 小时前
21.搜索二维矩阵 II
前端·javascript·算法·矩阵
不爱吃糖的程序媛3 小时前
Electron 应用中的系统检测方案对比
前端·javascript·electron
pe7er3 小时前
用高阶函数实现递归:从匿名函数到通用递归生成器
前端·javascript
zhousenshan3 小时前
Node.js后端框架Express.js
express
Jonathan Star3 小时前
NestJS 是基于 Node.js 的渐进式后端框架,核心特点包括 **依赖注入、模块化架构、装饰器驱动、TypeScript 优先、与主流工具集成** 等
开发语言·javascript·node.js
矢心4 小时前
setTimeout 和 setInterval:看似简单,但你不知道的使用误区
前端·javascript·面试
一枚前端小能手4 小时前
🧭 使用历史记录 API - SPA导航与状态管理的完整指南
前端·javascript