快速搭建一個(gè)TypeScript項(xiàng)目

在團(tuán)隊(duì)開發(fā)中為了更好的協(xié)作,我們應(yīng)該在項(xiàng)目中制定各種規(guī)則,比如:代碼風(fēng)格、變量命名、文件命名、git commit 提交格式等等。 這篇文章就介紹如何搭建快速搭建一個(gè)具有自定義規(guī)則的 TypeScript 項(xiàng)目。

首先在 GitHub 上創(chuàng)建一個(gè)倉庫,然后 clone 到本地。

$ git clone git@github.com:ZhiXiao-Lin/create-ts-project.git

進(jìn)入項(xiàng)目目錄,執(zhí)行 NPM 初始化

$ yarn init

安裝 typescript 作為開發(fā)階段的依賴項(xiàng)

$ yarn add typescript -D

在根目錄新建 tsconfig.json,配置項(xiàng)具體的意義可以參考 ts 官方文檔

{
    "version": "1.8.0",
    "compilerOptions": {
        "outDir": "build/compiled",
        "lib": [ "es6" ],
        "target": "es5",
        "module": "commonjs",
        "moduleResolution": "node",
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "sourceMap": true,
        "noImplicitAny": true,
        "declaration": true
    },
    "exclude": [ "build", "node_modules" ]
}

安裝 @types/node 讓 node 的核心包具備類型提示

$ yarn add @types/node -D

在根目錄新建 src 目錄,用于存放所有的 TypeScript 源文件,然后在 src 下新建 index.ts 作為入口文件

src/index.ts

console.log('Hello TypeScript!');

image.png

在開發(fā)階段為了能直接執(zhí)行并且監(jiān)聽 ts 文件的變化,安裝 ts-node-dev

$ yarn add ts-node-dev -D

在 package.json 中定義一個(gè)啟動(dòng)腳本

"scripts": {
    "start": "ts-node-dev --respawn --transpileOnly src/index.ts"
}

試著運(yùn)行

$ yarn start
yarn run v1.12.3
$ ts-node-dev --respawn --transpileOnly src/index.ts
Using ts-node version 8.0.1, typescript version 3.2.4
Hello TypeScript!

不管團(tuán)隊(duì)中的成員用的是什么編輯器,我們都應(yīng)該保持一致的代碼風(fēng)格,這就需要使用 prettier

$ yarn add prettier -D

然后在根目錄下新增一個(gè) .prettierrc.js,用于定義代碼格式化的規(guī)則

module.exports = {
    // 一行最多 140 字符
    printWidth: 140,
    // 使用 4 個(gè)空格縮進(jìn)
    tabWidth: 4,
    // 不使用縮進(jìn)符,而使用空格
    useTabs: false,
    // 行尾需要有分號(hào)
    semi: true,
    // 使用單引號(hào)
    singleQuote: true,
    // jsx 不使用單引號(hào),而使用雙引號(hào)
    jsxSingleQuote: false,
    // 末尾不需要逗號(hào)
    trailingComma: 'none',
    // 大括號(hào)內(nèi)的首尾需要空格
    bracketSpacing: true,
    // jsx 標(biāo)簽的反尖括號(hào)需要換行
    jsxBracketSameLine: false,
    // 箭頭函數(shù),只有一個(gè)參數(shù)的時(shí)候,也需要括號(hào)
    arrowParens: 'always',
    // 每個(gè)文件格式化的范圍是文件的全部?jī)?nèi)容
    rangeStart: 0,
    rangeEnd: Infinity,
    // 不需要寫文件開頭的 @prettier
    requirePragma: false,
    // 不需要自動(dòng)在文件開頭插入 @prettier
    insertPragma: false,
    // 使用默認(rèn)的折行標(biāo)準(zhǔn)
    proseWrap: 'preserve',
    // 根據(jù)顯示樣式?jīng)Q定 html 要不要折行
    htmlWhitespaceSensitivity: 'css',
    // 換行符使用 lf
    endOfLine: 'lf'
};

在 package.json 中新增一條 script

"scripts": {
    "start": "ts-node-dev --respawn --transpileOnly src/index.ts",
    "style:prettier": "prettier --write \"src/**/*.ts\""
},

運(yùn)行 yarn style:prettier 將會(huì)自動(dòng)格式化 src 目錄下的所有 .ts 文件

$ yarn style:prettier
yarn run v1.12.3
$ prettier --write "src/**/*.ts"
src\index.ts 225ms
Done in 0.66s.

安裝 tslint 用于檢查項(xiàng)目文件的命名、變量的命名等等

$ yarn add tslint -D

安裝 tslint-config-prettier ,這是根據(jù) prettier 定義的 tslint 規(guī)則

$ yarn add tslint-config-prettier -D

在根目錄下新建 tslint.json,根據(jù)自己的需要定義 rules

{
    "defaultSeverity": "error",
    "extend": [ "tslint-config-prettier" ], // 繼承 tslint-config-prettier
    "linterOptions": {
        "exclude": [ "**/node_modules/**" ]  // 排除 node_modules
    },
    "jsRules": {
        "no-unused-expression": true
    },
    "rules": {
        "typedef": {
            "options": [ "property-declaration" ]
        },
        "class-name": true,
        "interface-name": true,
        "variable-name": {
            "options": [ "ban-keywords", "check-format", "allow-leading-underscore", "allow-pascal-case" ]
        },
        "no-var-keyword": true,
        "no-var-requires": true,
        "no-any": false,
        "no-string-literal": true,
        "await-promise": true,
        "promise-function-async": true
    },
    "rulesDirectory": []
}

在 package.json 中新增一條 script

"scripts": {
    "start": "ts-node-dev --respawn --transpileOnly src/index.ts",
    "style:prettier": "prettier --write \"src/**/*.ts\"",
    "style:lint": "tslint -p tsconfig.json -c tslint.json"
},

運(yùn)行 yarn style:lint,會(huì)執(zhí)行 lint 檢查

$ yarn style:lint
yarn run v1.12.3
$ tslint -p tsconfig.json -c tslint.json
Done in 1.45s.

安裝 commitizen,讓我們的項(xiàng)目具有統(tǒng)一的 git commit 規(guī)范

$ npm install -g commitizen
$ commitizen init cz-conventional-changelog --save --save-exact
Attempting to initialize using the npm package cz-conventional-changelog
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN create-ts-project@1.0.0 No description

+ cz-conventional-changelog@2.1.0
added 7 packages from 16 contributors, removed 1 package, updated 131 packages and audited 219 packages in 10.509s
found 0 vulnerabilities

執(zhí)行后 package.json 中會(huì)多出 commitizen 的配置項(xiàng)

"config": {
    "commitizen": {
        "path": "./node_modules/cz-conventional-changelog"
    }
}

將所有的 git commit 操作替換成 git cz

 $ git cz
cz-cli@3.0.5, cz-conventional-changelog@2.1.0


Line 1 will be cropped at 100 characters. All other lines will be wrapped after 100 characters.

? Select the type of change that you're committing: (Use arrow keys)
> feat:     A new feature
  fix:      A bug fix
  docs:     Documentation only changes
  style:    Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)
  refactor: A code change that neither fixes a bug nor adds a feature
  perf:     A code change that improves performance
  test:     Adding missing tests or correcting existing tests
(Move up and down to reveal more choices)

我們還需要在 git 提交的時(shí)候進(jìn)行 commit 規(guī)范的檢查,首先安裝 validate-commit-msg 并在根目錄中新建一個(gè) .vcmrc 文件用于定義 commit 的驗(yàn)證規(guī)則

$ yarn add validate-commit-msg -D
{
    "types": [ "feat", "fix", "docs", "style", "refactor", "perf", "test", "build", "ci", "chore", "revert" ],
    "scope": {
        "required": false,
        "allowed": [ "*" ],
        "validate": false,
        "multiple": false
    },
    "warnOnFail": false,
    "maxSubjectLength": 100,
    "subjectPattern": ".+",
    "subjectPatternErrorMsg": "subject does not match subject pattern!",
    "helpMessage": "",
    "autoFix": true
}

然后安裝 husky 讓我們可以很方便的定義 git hooks

$  yarn add husky -D

在 package.json 中定義 git hooks,使用 validate-commit-msg 來檢查 commit 格式

"husky": {
        "hooks": {
            "commit-msg": "validate-commit-msg"
        }
}

現(xiàn)在如果提交的 commit 不符合 .vcmrc 定義的格式就會(huì)提交失敗

$ git commit -m "2223"
husky > commit-msg (node v10.14.0)
INVALID COMMIT MSG: does not match "<type>(<scope>): <subject>" !
2223
husky > commit-msg hook failed (add --no-verify to bypass)

現(xiàn)在我們還希望能在 commit 時(shí)自動(dòng)執(zhí)行代碼格式化和語法檢查,要使用一條命令執(zhí)行多項(xiàng)操作可以安裝 npm-run-all

$  yarn add npm-run-all -D

npm-run-all 提供兩個(gè)命令 run-s 串行執(zhí)行多條命令 run-p 并行執(zhí)行多條命令,在 package.json 中定義一個(gè) script,用于串行執(zhí)行所有以 style: 開頭的 script

"scripts": {
    "start": "ts-node-dev --respawn --transpileOnly src/index.ts",
    "style": "run-s style:**",
    "style:prettier": "prettier --write \"src/**/*.ts\"",
    "style:lint": "tslint -p tsconfig.json -c tslint.json"
},

運(yùn)行一下,看到確實(shí)執(zhí)行了兩條命令

$ yarn style
yarn run v1.12.3
$ run-s style:**
$ prettier --write "src/**/*.ts"
src\index.ts 229ms
$ tslint -p tsconfig.json -c tslint.json
Done in 3.02s.

修改 package.json 定義的 git hooks

"husky": {
    "hooks": {
        "pre-commit": "yarn style",
        "commit-msg": "validate-commit-msg"
    }
},

試著進(jìn)行一次提交

$ git add .
$ git cz
cz-cli@3.0.5, cz-conventional-changelog@2.1.0


Line 1 will be cropped at 100 characters. All other lines will be wrapped after 100 characters.

? Select the type of change that you're committing: feat:     A new feature
? What is the scope of this change (e.g. component or file name)? (press enter to skip)

? Write a short, imperative tense description of the change:
 infrastructure
? Provide a longer description of the change: (press enter to skip)

? Are there any breaking changes? No
? Does this change affect any open issues? No
husky > pre-commit (node v10.14.0)
yarn run v1.12.3
$ run-s style:**
$ prettier --write "src/**/*.ts"
src\index.ts 228ms
$ tslint -p tsconfig.json -c tslint.json
Done in 3.01s.
husky > commit-msg (node v10.14.0)
[master 5c75d75] feat: infrastructure
 6 files changed, 2666 insertions(+)
 create mode 100644 package-lock.json
 create mode 100644 package.json
 create mode 100644 src/index.ts
 create mode 100644 tsconfig.json
 create mode 100644 tslint.json
 create mode 100644 yarn.lock

確實(shí)在提交前格式化了所有代碼文件,并且進(jìn)行了 commit 檢查,至此我們的團(tuán)隊(duì)協(xié)作項(xiàng)目就搭建好了,再也不用擔(dān)心五花八門的代碼格式和 commit 提交說明了。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容