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" 命令启动工程进行测试。

相关推荐
黑客飓风20 分钟前
JavaScript 性能优化实战大纲
前端·javascript·性能优化
YeeWang3 小时前
🎉 Eficy 让你的 Cherry Studio 直接生成可预览的 React 页面
前端·javascript
gnip3 小时前
Jenkins部署前端项目实战方案
前端·javascript·架构
Orange3015113 小时前
《深入源码理解webpack构建流程》
前端·javascript·webpack·typescript·node.js·es6
李明卫杭州4 小时前
CSS `clamp()` 函数详解
javascript
奶丝兔蜜柚5 小时前
栈溢出优化
javascript
小高0075 小时前
📈前端图片压缩实战:体积直降 80%,LCP 提升 2 倍
前端·javascript·面试
BillKu5 小时前
vue3+element-plus 输入框el-input设置背景颜色和字体颜色,样式效果等同于不可编辑的效果
前端·javascript·vue.js
NeilNiu6 小时前
开源AI工具Midscene.js
javascript·人工智能·开源
Warren986 小时前
软件测试-Selenium学习笔记
java·javascript·笔记·学习·selenium·测试工具·安全