前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >express 项目支持 typescript 实战

express 项目支持 typescript 实战

作者头像
kongxx
发布2024-01-24 08:28:47
2040
发布2024-01-24 08:28:47
举报

首先创建一个express项目

  • 初始化项目
代码语言:javascript
复制
mkdir myapp
cd myapp
npm init (都用默认值)
  • 添加依赖包
代码语言:javascript
复制
npm install express nodemon
  • 修改 package.json
代码语言:javascript
复制
{
  "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
代码语言:javascript
复制
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使用的包
代码语言:javascript
复制
npm install -D typescript @types/express @types/node

npm install -D ts-node
  • 生成 tsconfig.json
代码语言:javascript
复制
npx tsc --init

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

代码语言:javascript
复制
{
  "compilerOptions": {
    "target": "es2016",
    "module": "commonjs",
    "outDir": "./dist",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  }
}
  • 将 src/index.js 改名成 src/index.ts,内容改成typescript脚本
代码语言:javascript
复制
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,内容如下
代码语言:javascript
复制
{
  "name": "myapp",
  "version": "1.0.0",
  "description": "",
  "main": "src/index.ts",
  "scripts": {
    "build": "npx tsc",
    "start": "node dist/index.ts",
    "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” 命令启动工程进行测试。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2024-01-23,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 首先创建一个express项目
  • express + typescript 改造
相关产品与服务
腾讯云服务器利旧
云服务器(Cloud Virtual Machine,CVM)提供安全可靠的弹性计算服务。 您可以实时扩展或缩减计算资源,适应变化的业务需求,并只需按实际使用的资源计费。使用 CVM 可以极大降低您的软硬件采购成本,简化 IT 运维工作。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档