如何在Node.js和Express中设置TypeScript(2023年)

如何在Node.js和Express中设置TypeScript(2023年)

在这篇文章中,我们将介绍在Express应用程序中设置TypeScript的最佳方法,了解与之相关的基本限制。

文章目录

创建初始文件夹和package.json

shell 复制代码
mkdir node-express-typescript
cd node-express-typescript
npm init --yes

在初始化package.json文件之后,新创建的文件可能会像下面的代码一样:

json 复制代码
{
  "name": "Your File Name",
  "version": "1.0.0",
  "description": "",
  "main": "index.ts", // 将入口点从js更改为.ts
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "type": "module",
  "keywords": [],
  "author": "",
  "license": "ISC"
}

安装TypeScript和其他依赖项

sh 复制代码
npm install express mongoose cors mongodb dotenv
sh 复制代码
npm install  -D typescript ts-node-dev @types/express @types/cors

生成tsconfig.json文件

bash 复制代码
npx tsc --init

上述命令将生成一个名为tsconfig.json的新文件,其中包含以下默认的编译器选项:

bash 复制代码
target: es2016
module: commonjs
strict: true
esModuleInterop: true
skipLibCheck: true
forceConsistentCasingInFileNames: true
  • 在打开tsconfig.json文件后,您会看到许多其他被注释掉的编译器选项。在tsconfig.json中,compilerOptions是一个必填字段,需要指定。

    • 将rootDir和outDir设置为src和dist文件夹
json 复制代码
{
  "compilerOptions": {
    "outDir": "./dist"

    // other options remain same
  }
}

使用.ts扩展名创建一个Express服务器

创建一个名为index.ts的文件并打开它

typescript 复制代码
import express, { Express, Request, Response , Application } from 'express';
import dotenv from 'dotenv';

//For env File 
dotenv.config();

const app: Application = express();
const port = process.env.PORT || 8000;

app.get('/', (req: Request, res: Response) => {
  res.send('Welcome to Express & TypeScript Server');
});

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

监听文件更改并构建目录

bash 复制代码
npm install  nodemon

安装这些开发依赖项后,更新package.json文件中的脚本:

bash 复制代码
{

  "scripts": {
    "build": "npx tsc",
    "start": "node dist/index.js",
    "dev": "nodemon index.ts"
  }
}

运行代码

bash 复制代码
npm run dev 

如果一切正常,您将在控制台中看到以下消息:

Server is Fire at http://localhost:8000

相关推荐
岁月宁静25 分钟前
图像生成接口的工程化设计与落地实践:封装豆包图像生成模型 Seedream 4.0 API
前端·人工智能·node.js
慢知行1 小时前
从 0 到 1 搭建 Vite+Vue3+TS 工程模板:能上手操作的指南
前端·vue.js·typescript
濮水大叔1 小时前
VonaJS业务抽象层: 验证码体系
typescript·nodejs·nestjs
锦瑟弦音16 小时前
2048游戏开发笔记4 & 音效 cocos3.8.7
笔记·typescript·cocos2d
云外天ノ☼1 天前
一、Node.js入门实战指南:从零搭建你的第一个后端
前端·javascript·笔记·node.js
Dontla1 天前
npm install命令介绍
前端·npm·node.js
xiecoding.cn2 天前
NPM下载和安装图文教程(附安装包)
npm·node.js·npm install·npm安装·npm是什么·安装npm·npm下载
“负拾捌”2 天前
基于NodeJs实现一个MCP客户端(会话模式和无会话模式)
javascript·ai·node.js·大模型·mcp
Luna-player2 天前
npm : 无法加载文件 C:\Program Files\nodejs\npm.ps1,因为在此系统上禁止运行脚本,解决方法
前端·npm·node.js
Mountain082 天前
解决 Node.js 启动报错:digital envelope routines 错误全记录
javascript·npm·node.js