使用vscode写typescript(node.js环境)起手式

动机

一直想把typescript在服务端开发中用起来,主要原因有:

  • javascript很灵活,但记忆力不好的话,的确会让你头疼,看着一月前自己写的代码,一脸茫然。
  • 类型检查有利有敝,但在团队开发中,限制个人的天马行空还是很有效的;
  • node对模块等es6特性的支持不尽人意,目前我只用node长期支持版所能支持的特性,个人不愿用babel之类的工具;
  • 开始用webstorm开发,结果它象visual studio系列一样,越来越臃肿;转而用vscode,但它的绝配是typescript;

问题

之前也陆陆续续试着用了,但总被一些困难绊住了,主要有以下几点:

  • vscode开发调试typescript环境的搭建,因为vscode版本更新也快,网上资料繁杂;
  • tsconfig.json的配置
  • tslint.json的配置
  • 全局变量的使用与设定;

解决

经过多次的不断尝试,今天终于达到自己满意的地步了。

环境搭建,基于最新版(1.26.1)

安装node.js

从官网下载对应操作系统的安装包,按说明安装。

全局安装typescript

    npm i -g typescript
生成并配置tsconfig.json

运行命令:


    tsc --init

配置文件:


{
  "compilerOptions": {
    "target": "es2017",                         // 指定 ECMAScript 目标版本: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'
    "module": "commonjs",                       // 指定使用模块: 'commonjs', 'amd', 'system', 'umd' or 'es2015'
    "moduleResolution": "node",                 // 选择模块解析策略: 'node' (Node.js) or 'classic' (TypeScript pre-1.6)
    "emitDecoratorMetadata": true,              // 为装饰器提供元数据的支持
    "experimentalDecorators": true,             // 启用装饰器
    "allowSyntheticDefaultImports": true,       // 允许从没有设置默认导出的模块中默认导入。
    "strict": true,                             // 启用所有严格类型检查选项
    "noImplicitAny": true,                      // 在表达式和声明上有隐含的 any类型时报错
    "alwaysStrict": true,                       // 以严格模式检查没个模块,并在没个文件里加入 'use strict'
    "sourceMap": true,
    "noEmit": false,                            // 不生成输出文件
    "removeComments": true,                     // 删除编译后的所有的注释
    "importHelpers": true,                      // 从 tslib 导入辅助工具函数
    "strictNullChecks": true,                   // 启用严格的 null 检查
    "lib": ["es2017"],                          // 指定要包含在编译中的库文件
    "typeRoots": ["node_modules/@types"],
    "types": [
      "node",
    ],
    "outDir": "./dist",
    "rootDir": "./src"
  },
  "include": [                                 // 需要编译的ts文件一个*表示文件匹配**表示忽略文件的深度问题
    "./src/*.ts",
    "./src/**/*.ts"
  ],
  "exclude": [
    "node_modules",
    "dist",
    "**/*.test.ts",
    "public"
  ]
}
生成项目配置package.json

运行命令:


    npm init

配置文件:


    {
  "name": "arest",
  "version": "0.1.0",
  "description": "a rest server use kao2, typescript & mongo db.",
  "main": "app.ts",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/zhoutk/arest.git"
  },
  "keywords": [
    "rest",
    "koa2",
    "typescript",
    "mongo"
  ],
  "dependencies": {
    "koa": "^2.5.2"
  },
  "author": "zhoutk@189.cn",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/zhoutk/arest/issues"
  },
  "homepage": "https://github.com/zhoutk/arest#readme",
  "devDependencies": {
    "@types/koa": "^2.0.46",
    "@types/node": "^10.9.4",
    "tslint": "^5.11.0",
    "typescript": "^3.0.3"
  }
}
监测文件改动并编译

运行命令:


    tsc -w
配置vscode项目启动launch.json

配置好后,按F5即可开始调试运行程序


{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "启动程序",
            "program": "${workspaceFolder}/dist/app.js",
            "outFiles": [
                "${workspaceFolder}/**/*.js"
            ]
        }
    ]
}

tslint的配置与生效

使用tslint可以定制团队共同使用的一些编码规则,这里需要注意的是,不但要全局安装typescript,tslint,还要在项目中安装,不然不能生效。这个鬼折腾了我好久!


{
    "rules": {
        "class-name": true,
        "comment-format": [
            false,
            "check-space"
        ],
        "indent": [
            true,
            "spaces"
        ],
        "no-duplicate-variable": true,
        "no-eval": true,
        "no-internal-module": true,
        "no-trailing-whitespace": false,
        "no-var-keyword": true,
        "one-line": [
            true,
            "check-open-brace",
            "check-whitespace"
        ],
        "quotemark": [
            true,
            "single"
        ],
        "semicolon": [true, "never"],
        "triple-equals": [
            true,
            "allow-null-check"
        ],
        "typedef-whitespace": [
            true,
            {
                "call-signature": "nospace",
                "index-signature": "nospace",
                "parameter": "nospace",
                "property-declaration": "nospace",
                "variable-declaration": "nospace"
            }
        ],
        "variable-name": [
            true,
            "ban-keywords"
        ],
        "whitespace": [
            true,
            "check-branch",
            "check-decl",
            "check-operator",
            "check-separator",
            "check-type"
        ]
    }
}

全局变量的使用

全局变量虽然不能滥用,便也不能没有,以下几点是关键:

  • tsconfig.json中加入 "types": [ "node"]
  • npm i @types/node
  • 建立globals.d.ts(文件名可以随意取),在其中声名全局变量(这是让ide知道)
  • 在入口文件(app.ts)中引入全局模块并赋值给node的全局变量global(这是让代码知道)

项目地址

这个项目我准备将express+mysql的成功经验移植到koa2+mongo中来。


https://github.com/zhoutk/arest

使用方法


git clone https://github.com/zhoutk/arest
cd arest
npm i

tsc -w
用vscode打开项目,并按F5运行       

小结

终于迈入typescript坑中,痛并快乐着!

来源:https://segmentfault.com/a/1190000016305647

原文地址:https://www.cnblogs.com/qixidi/p/10179330.html