使用 TypeScript 设置 Express 服务器 📡
Express.js 是一个基于 Node.js 的 Web 应用框架。它提供了一个简洁的接口,包含了构建 Web 应用所需的所有工具。Express.js 还提供了丰富的模块,这些模块可通过 npm 获取,您可以根据需要直接将其集成到 Express 中,从而为应用增添了灵活性。
步骤 1:创建.gitignore文件
在其中添加node_modules/和.env,因为我们不希望 node 模块被推送到 GitHub,也不希望我们的密钥公开可用。
node_modules/
.env
步骤 2:添加依赖项
您可以使用yarn或npm(我这里使用的是 yarn)。
yarn 添加依赖项
yarn add -D 用于开发依赖项
注意:我们之后可能会添加更多内容……并会在开发过程中进行讨论。此外,您使用的版本可能更新,或者某些软件包将来可能会被弃用。另外,由于我们使用 TypeScript,因此需要为所有添加的依赖项定义类型(@types)。
下面列出的依赖项是我认为服务器启动和运行所必需的基本依赖项。
"dependencies": {
"colors": "^1.4.0",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
},
"devDependencies": {
"@types/cors": "^2.8.9",
"@types/express": "^4.17.9",
"concurrently": "^5.3.0",
"nodemon": "^2.0.6"
}
步骤 3:创建 tsconfig.json 文件并添加以下内容
配置 TypeScript
您可以查阅官方文档,了解更多关于配置 TypeScript 的信息,并研究更多可用的参数,以便根据您的需要使用。
{
"compilerOptions": {
/* Basic Options */
"target": "es6" /* Specify ECMAScript target version. */,
"module": "commonjs" /* Specify module code generation. */,
"sourceMap": false /* Generates corresponding '.map' file. */,
"outDir": "./dist" /* Redirect output structure to the directory. */,
"rootDir": "./src" /* Specify the root directory of input files. */,
/* Strict Type-Checking Options */
"strict": true /* Enable all strict type-checking options. */,
/* Module Resolution Options */
"moduleResolution": "node" /* Specify module resolution strategy. */,
"baseUrl": "./" /* Base directory to resolve non-absolute module names. */,
"paths": {
"*": ["node_modules/", "src/types/*"]
} ,
"esModuleInterop": true ,
/* Advanced Options */
"skipLibCheck": true /* Skip type checking of declaration files. */,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*"],
"exclude": ["src/types/*.ts", "node_modules", ".vscode"]
}
步骤 4:创建主文件
在您的目录中创建一个名为 src 的文件夹,并添加一个app.ts文件,内容如下,即可启动并运行您的 express 服务器。
相对路径:src/app.ts
import express, { Application, json, Request, Response } from "express";
import "colors";
import cors from "cors";
import { config } from "dotenv";
config();
const app: Application = express();
app.use(cors());
app.use(json());
const PORT: string | number = process.env.PORT || 5000;
const ENV: string = process.env.NODE_ENV || "development";
app.get("/", (_req: Request, res: Response) => {
return res.send("API Running...");
});
app.listen(PORT, () =>
console.log(
` 📡 Backend server: `.inverse.yellow.bold +
` Running in ${ENV} mode on port ${PORT}`
)
);
步骤五:设置运行脚本
将以下内容添加到package.json文件中
"scripts": {
"watch-ts": "tsc -w",
"server": "nodemon dist/app.js",
"dev": "concurrently -k -p \"[{name}]\" -n \"Typescript,Node\" -c \"blue.bold,yellow.bold\" \"yarn run watch-ts\" \"yarn run server\" "
}
现在运行“ yarn run dev ”来启动我们的服务器,瞧,我们的服务器已经启动并运行了。
你应该在终端输出中看到这些内容,并且你的项目中应该会出现dist/目录,其中包含所有使用 ES6 语法的 JavaScript 代码。
此外,还有一个ts-node包,它使用 TypeScript 文件运行 node 服务器,而无需生成任何 JavaScript 文件。
文章来源:https://dev.to/tejastn10/setting-up-express-server-with-typescript-3dg5
