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

前言

为何要用TypeScript

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

Cannot read property 'xxx' of undefined
'xxx' is not a function/object
'xxx' is not defined
复制代码

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

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

编译器推荐使用VS CODE,对TyepScript的支持很是友好npm

开始

初始化项目

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

快速的建立一个package.jsonsegmentfault

npm init -y
复制代码

安装TypeScriptbash

npm install typescript -s
复制代码

新建tsconfig.json文件服务器

tsc --init
复制代码

tsconfig.json结构以下app

{
  "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文件夹,此时的目录结构为post

├──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了。

若是个人文章对你有帮助,能够点赞鼓励一下

相关文章
相关标签/搜索