如何用Express和TypeScript建立一个NodeJS应用程序

325 阅读3分钟

Node.js是一个开源的、跨平台的、后端的JavaScript运行环境,在V8引擎上运行,在网络浏览器之外执行JavaScript代码。Node.js让开发者使用JavaScript编写命令行工具和服务器端脚本--在页面被发送到用户的网络浏览器之前,在服务器端运行脚本以产生动态网页内容。因此,Node.js代表了一种 "到处都是JavaScript "的范式,围绕一种单一的编程语言统一网络应用程序开发,而不是为服务器端和客户端的脚本提供不同的语言。

Express.js是Node.js的一个后端网络应用框架,在MIT许可下作为免费开源软件发布。它是为构建网络应用和API而设计的。它被称为Node.js的事实上的标准服务器框架。

TypeScript是一种由微软开发和维护的编程语言。它是JavaScript的一个严格的语法超集,并为语言增加了可选的静态类型。它是为开发大型应用程序而设计的,并可转译为JavaScript。

项目结构

node-express-typescript/
--build/
  --app.js
--src/
  --api.ts
--package.json
--tsconfig.json

**第一步:**让我们从头开始,创建一个node-express-typescript文件夹

**第二步:**打开终端,在该文件夹的根部运行npm init 。并填写所有的字段,或者直接按回车键,跳过所有的。

结果,你应该看到在你的项目的根部创建了一个package.json文件。

{
  "name": "node-express-typescript",
  "version": "1.0.0",
  "description": "How to Setup a Node Express with TypeScript",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

**第3步:**现在让我们安装expressnpm i express ,并作为dev依赖项安装。npm i -D typescript @types/node @types/express

{
  "name": "node-express-typescript",
  "version": "1.0.0",
  "description": "How to Setup a Node Express with TypeScript",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.1"
  },
  "devDependencies": {
    "@types/express": "^4.17.13",
    "@types/node": "^18.0.0",
    "typescript": "^4.7.4"
  }
}

第**4步:**为了初始化tsconfig.json文件,运行npx tsc --init

结果,你应该看到在你项目的根部生成了一个tsconfig.json文件。

然后打开它并调整2个选项

"outDir": "./build",    /* Specify an output folder for all emitted files. */
"rootDir": "./src",     /* Specify the root folder within your source files. */

**第5步:**创建一个src 文件夹并在该文件夹中创建一个名为app.ts的文件

import express, { Application, Request, Response } from 'express';

const app: Application = express();

const PORT: number = 3001;

app.use('/', (req: Request, res: Response): void => {
    res.send('Hello world!');
});

app.listen(PORT, (): void => {
    console.log('SERVER IS UP ON PORT:', PORT);
});

**第6步:**为了建立一个项目,在你的项目根部运行npx tsc 命令

结果,你应该看到在你的项目中编译了app.js文件的构建文件夹。

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = __importDefault(require("express"));
const app = (0, express_1.default)();
const PORT = 3001;
app.use('/', (req, res) => {
    res.send('Hello world!');
});
app.listen(PORT, () => {
    console.log('SERVER IS UP ON PORT:', PORT);
});

**第7步:**让我们测试一下,在你的package.json文件中添加一个新的脚本并运行npm start

  "scripts": {
    "start": "node ./build/app.js"
  }

结果,你应该在你的终端上看到

node-express-typescript yuraabharian$ npm start

> [email protected] start
> node ./build/app.js

SERVER IS UP ON PORT: 3001

**第8步:**在你的浏览器中运行http:localhost:3001

一个小建议:我们可以通过更新我们的启动脚本使这个过程更快一些,这样你就可以建立你的应用程序并立即运行它了

  "scripts": {
    "start": "npx tsc && node ./build/app.js"
  }

**注意:**你可以在我的Github上找到我的示例代码。