使用vscode寫typescript(node.js環境)起手式

動機

一直想把typescript在服務端開發中用起來,主要緣由有:javascript

  • javascript很靈活,但記憶力很差的話,的確會讓你頭疼,看着一月前本身寫的代碼,一臉茫然。
  • 類型檢查有利有敝,但在團隊開發中,限制我的的天馬行空仍是頗有效的;
  • node對模塊等es6特性的支持不盡人意,目前我只用node長期支持版所能支持的特性,我的不肯用babel之類的工具;
  • 開始用webstorm開發,結果它象visual studio系列同樣,愈來愈臃腫;轉而用vscode,但它的絕配是typescript;

問題

以前也陸陸續續試着用了,但總被一些困難絆住了,主要有如下幾點:java

  • vscode開發調試typescript環境的搭建,由於vscode版本更新也快,網上資料繁雜;
  • tsconfig.json的配置
  • tslint.json的配置
  • 全局變量的使用與設定;

解決

通過屢次的不斷嘗試,今天終於達到本身滿意的地步了。node

環境搭建,基於最新版(1.26.1)

安裝node.js

從官網下載對應操做系統的安裝包,按說明安裝。mysql

全局安裝typescript
npm i -g typescript
生成並配置tsconfig.json

運行命令:git

tsc --init

配置文件:es6

{
  "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

運行命令:github

npm init

配置文件:web

{
  "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"
  }
}
監測文件改動並編譯

運行命令:sql

tsc -w
配置vscode項目啓動launch.json

配置好後,按F5便可開始調試運行程序typescript

{
    "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坑中,痛並快樂着!

相關文章
相關標籤/搜索