Google TypeScript Style

【 TypeScript 】建立 Google TypeScript Style 的 Node.js 環境

之前雖然寫過 【 Node.js 】如何在 Node.js 中建立 TypeScript 的環境,但並沒有導入 ESLint 和 Prettier 來決定 coding style,這篇簡單記錄一下如何建立 Google TypeScript Style 的 Node.js 環境。

Google 有將該 style guide 包成套件 ( gts ) 方便專案引入使用,因此我們直接根據 gts 的 document 來 import google TypeScript style guide。

1. 安裝 gts ( google typescript style )

$ npx gts init

import gts 後 package.json 被更新為:

{
  "name": "",
  "version": "0.0.0",
  "description": "",
  "main": "build/src/index.js",
  "types": "build/src/index.d.ts",
  "files": [
    "build/src"
  ],
  "license": "Apache-2.0",
  "keywords": [],
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "lint": "gts lint",
    "clean": "gts clean",
    "compile": "tsc",
    "fix": "gts fix",
    "prepare": "npm run compile",
    "pretest": "npm run compile",
    "posttest": "npm run lint"
  },
  "devDependencies": {
    "gts": "^3.1.0",
    "typescript": "^4.0.3",
    "@types/node": "^14.11.2"
  }
}

新增了一些 script 來輔助修正 TypeScript 的 style,並且安裝了 TypeScript,也自動 init 了 tsconfig.json,目前的檔案結構:

├── .eslintignore
├── .eslintrc.json
├── .prettierrc.js
├── package-lock.json
├── package.json
├── src
│   └── index.ts
└── tsconfig.json

2. 在 vscode 安裝 ESLint

可以看到 gtc 是用 eslint 來設定 TypeScript 的 style,我們可以安裝 vs-code 的套件:ESLint 來輔助開發,這樣寫 code 的過程中這個套件就會自動幫你檢查寫出來的 style 是否有符合設定檔,不用等到去執行 script 才知道專案種哪個地方不符合。

Google TypeScript Style

如此一來一旦檔案中有任何不符合格式的地方,都會有紅色毛毛蟲出現,並且會提示不符合哪個規則:

Node.js

如果覺得我的文章有幫助的話,歡迎幫我的粉專按讚哦~謝謝你!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top