基于TypeScript+Node.js+Express搭建服务器

10,841

前言

为什么要用TypeScript

鉴于JavaScript弱类型语言动态类型语言,因此JavaScript在变量声明的时候无需指定变量的类型,在声明之后便可为其赋值不同的类型。因此在多人团队的开发里面,JavaScript的这种“便捷”反而会带来很多麻烦。

Cannot read property 'xxx' of undefined
'xxx' is not a function/object
'xxx' is not defined

TypeScript就是为了解决JavaScript的问题而产生。 与JavaScript截然相反,TypeScript使用的是强类型语言静态类型语言,有写过Java的同学应该会感到非常亲切。TypeScript在多人团队开发时候便成为了不错的选择。

强/弱类型、动/静类型、GC 和 VM,你真的分清楚了么?

编译器推荐使用VS CODE,对TyepScript的支持非常友好

开始

初始化项目

在你的项目新建一个文件夹,如helloTS,打开helloTS

快速的创建一个package.json

npm init -y

安装TypeScript

npm install typescript -s

新建tsconfig.json文件

tsc --init

tsconfig.json结构如下

{
  "compilerOptions": {
    ···
    // "declarationMap": true,                /* Generates a sourcemap for each corresponding '.d.ts' file. */
    // "sourceMap": true,                     /* Generates corresponding '.map' file. */
    // "outFile": "./",                       /* Concatenate and emit output to single file. */
    // "outDir": "./",                        /* Redirect output structure to the directory. */
    // "rootDir": "./",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    ···
  }
}

在helloTS目录下新建build、src文件夹,此时的目录结构为

    ├──helloTS
       ├──build
       ├──src
       └──tsconfig.json

将tsconfig.json下的outDir路径修改为./buildrootDir路径修改为./src

此时tsconfig.json结构如下

{
  "compilerOptions": {
    ···
    // "sourceMap": true,                     /* Generates corresponding '.map' file. */
    // "outFile": "./",                       /* Concatenate and emit output to single file. */
    // "outDir": "./build",                   /* Redirect output structure to the directory. */
    // "rootDir": "./src",                    /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    // "composite": true,                     /* Enable project compilation */
    // "tsBuildInfoFile": "./",               /* Specify file to store incremental compilation information */
    ···
  }
}

至此,tsconfig.json的配置到此结束,其余配置可查阅tsconfig配置文档

安装Express

npm install express -s

由于我们使用到了TypeScript,因此需要继续引入相应的d.ts来识别

npm install @types/express -s

开始编写

在我们的项目helloTS中,我们将创建一个名为的文件夹app作为启动项。在此文件夹中,我们将创建一个名为app.ts以下内容的文件,此时的目录结构为

    ├──helloTS
       ├──build
       ├──src
          ├──app
             ├──app.ts
       └──tsconfig.json

app.ts

import express = require('express');

// Create a new express application instance
const app: express.Application = express();

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(3000, ()=> {
  console.log('Example app listening on port 3000!');
});

进行编译

执行命令行

tsc

你会发现build目录里生成了相应的js代码,目录结构如下

    ├──helloTS
       ├──build
          ├──app
             ├──app.js
       ├──src
          ├──app
             ├──app.ts
       └──tsconfig.json

再次执行命令行

node ./build/app/app.js

若提示Example app listening on port 3000!,恭喜你已经成功搭建好一个相对简陋的服务器了。

问题

TypeScript调试

经过上述的操作,我们会发现每次编译的时候都需要使用tsc构建,然后再通过node开启服务,若要进行开发,则会大大降低开发效率。

解决方法

使用ts-node

参考使用ts-node和vsc来调试TypeScript代码

首先安装ts-node

npm install ts-node -s-d

打开.vscode/launch.json配置文件(如果没有此文件,请点击菜单栏的调试->打开配置)修改为

{
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "启动程序",
            "runtimeArgs": [
                "--nolazy",
                "-r",
                "ts-node/register"
            ],
            "args": [
                "${workspaceRoot}/src/app/app.ts"
            ],
            "env": { "TS_NODE_PROJECT": "tsconfig.json" },
            "sourceMaps": true,
            "cwd": "${workspaceRoot}",
            "protocol": "inspector",
            "console": "integratedTerminal",
            "internalConsoleOptions": "neverOpen"
        }
    ]
}

之后直接在VS Code上按F5刷新即可开启,这下就可以愉快地调试Ts了。

如果我的文章对你有帮助,可以点赞鼓励一下