1. 程式人生 > >使用vscode寫typescript(node.js環境)起手式

使用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": "
[email protected]
", "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