cocos creator + typescript + eslint + prettier boilerplate

項目repo: https://github.com/R4M80MrX/cocos-creator-boilerplate

準(zhǔn)備工作

環(huán)境配置:

  • Win10 64 位操作系統(tǒng)
  • cocos creator v2.2.1 +
  • NodeJS v10.16.1 +
  • Yarn v1.19.2 +
  • VSCode
  • git

第一步 新建 cocos creator typescript 工程

2019-12-11-22-03-52.png

全點一遍


2019-12-11-22-05-40.png

至此, 一個干凈的 Hello typescript 項目創(chuàng)建完成

第二步 初始化 npm 項目

編輯器右上角打開項目所在位置, 在 VSCode 中打開項目根目錄


2019-12-11-22-11-59.png

在項目根目錄執(zhí)行命令(后續(xù)操作如無特殊說明均在項目根目錄進(jìn)行)
yarn 初始化工程

yarn init -y

根目錄下生成 package.json 文件

{
  "name": "my-cocos-demo",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT"
}

.gitignore 進(jìn)行修改
刪除

#//////////////////////////
# VS Code
#//////////////////////////

.vscode/

將 vscode 項目配置加入版本控制

添加

# dependencies
node_modules

# we use yarn
package-lock.json

# misc
npm-debug.log
yarn-error.log

lerna-debug.log

將 node 模塊, npm 鎖文件, 和一些 log 文件排除在外

執(zhí)行

git init

初始化 git 倉庫

執(zhí)行

git add .
git commit -m 'first commit'

進(jìn)行第一次提交

至此, npm 項目初始化完成

第三步 添加項目配置

VSCode 安裝插件

  • ESlint // 代碼格式檢查
  • Prettier // 代碼格式美化
  • EditorConfig for VS Code // 編輯器統(tǒng)一配置

EditorConfig 的安裝及配置

根目錄創(chuàng)建 .editorconfig

# http://editorconfig.org
root = true

[{assets}/**.{ts,json,js}]
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
indent_style = space
indent_size = 2

Prettier 的安裝及配置

執(zhí)行

yarn add -D prettier

安裝 prettier

創(chuàng)建 .prettierrc

module.exports = {
  endOfLine: "lf",
  proseWrap: "always",
  singleQuote: true,
  trailingComma: "es5"
};

創(chuàng)建 .prettierignore

lib/
build/

*.html

至此, Prettier 配置完畢

ESlint 的安裝及配置

airbnb-config 官方給出的安裝方法是

npx install-peerdeps --dev eslint-config-airbnb-base

在我這里要么跳過安裝要么報連接錯誤, 只好手動安裝

執(zhí)行

npm info "eslint-config-airbnb-base@latest" peerDependencies

輸出類似以下內(nèi)容, 版本號可能不同

{ "eslint": "^5.16.0 || ^6.1.0", "eslint-plugin-import": "^2.18.2" }

按照此版本安裝 eslint-config-airbnb-base 及其依賴

yarn add -D eslint@6.1.0 eslint-plugin-import@2.18.2 eslint-config-airbnb-base

執(zhí)行

yarn add -D babel-eslint eslint-config-prettier

安裝 babel-eslint 解析器和 eslint-config-prettier ESlint Prettier 配置插件

執(zhí)行

yarn add -D @typescript-eslint/eslint-plugin @typescript-eslint/parser

安裝 ESlint typescript 插件
此處遇到一個問題, latest 的 typescript-eslint 版本使用了 eslint 的新方法 function-call-argument-newline 在 ESlint@^6.2 才有, 而之前與 airbnb 同時安裝的版本是 6.1.0 報錯, 于是重新安裝了最新的 ESlint

執(zhí)行

yarn add typescript

安裝 typescript

創(chuàng)建 .vscode/settings.json 來打開 VSCode 對 eslint 的支持

{
  "eslint.enable": true,
  "typescript.tsdk": "node_modules/typescript/lib",
  "eslint.validate": [
    "javascript",
    {
      "language": "typescript",
      "autoFix": true
    }
  ]
}

創(chuàng)建 .eslintrc

{
  "extends": ["airbnb-base", "prettier"],
  "parser": "babel-eslint",
  "globals": {
    "cc": true
  },
  "rules": {
    "no-underscore-dangle": "off"
  },
  "parserOptions": {
    "ecmaFeatures": {
      "legacyDecorators": 1
    }
  }
}

此時已完成 ESlint + cocos creator 的基本配置, 打開 assets/Script/Helloworld.ts
start() {} 中輸入

2019-12-12-08-30-14.png

已經(jīng)可以看到 ESlint 的報錯了

至此, ESlint 的基本配置完成

修改 ESlint 規(guī)則

airbnb 的 ESlint 配置對代碼有嚴(yán)格的要求, 在使用過程中會有許多摸不著頭腦的錯誤, 可以通過修改 .eslintrc 文件自定義規(guī)則

ESlint 有非常多的規(guī)則, 此處僅貼出一份我自用的, 根據(jù)平時寫前端的 .eslintrc 修改而來的規(guī)則, 不再詳細(xì)列舉每一條的意義, 可以自行百度每一條規(guī)則的名字查看詳細(xì)信息

{
  "extends": ["airbnb-base", "prettier"],
  "parser": "babel-eslint",
  "env": {
    "browser": true,
    "node": true,
    "jest": true,
    "es6": true
  },
  "globals": {
    "cc": true,
    "VERSION": true,
    "TimeoutID": true,
    "object": true,
    "__DEV__": true
  },
  "rules": {
    "import/no-extraneous-dependencies": 0,
    "import/no-cycle": "warn",
    "arrow-parens": 0,
    "prefer-destructuring": 0,
    "no-async-promise-executor": "warn",
    "import/prefer-default-export": 0,
    "class-methods-use-this": 0,
    "no-console": 0,
    // "no-console": ["warn", { "allow": ["error", "warn"] }],
    "prefer-template": "off",
    "no-plusplus": 0,
    "no-underscore-dangle": "off",
    "no-nested-ternary": "warn",
    "import/no-named-default": 0,
    "import/no-webpack-loader-syntax": 0,
    "import/extensions": [
      "error",
      "always",
      {
        "ts": "never",
        "tsx": "never",
        "js": "never"
      }
    ],
    "import/default": "error",
    "no-param-reassign": [
      "error",
      {
        "props": false
      }
    ],
    "camelcase": 0,
    "no-bitwise": "off",
    "arrow-body-style": ["error", "as-needed"],
    "no-restricted-globals": "off",
    "lines-between-class-members": [
      "error",
      "always",
      {
        "exceptAfterSingleLine": true
      }
    ]
  },
  "overrides": [
    {
      "files": ["**/*.ts"],
      "parser": "@typescript-eslint/parser",
      "parserOptions": {
        "ecmaVersion": 2018,
        "sourceType": "module",
        "warnOnUnsupportedTypeScriptVersion": true
      },
      "plugins": ["@typescript-eslint"],
      "rules": {
        "default-case": "off",
        "no-dupe-class-members": "off",
        "no-array-constructor": "off",
        "@typescript-eslint/no-array-constructor": "warn",
        "@typescript-eslint/no-namespace": "error",
        "no-use-before-define": "off",
        "@typescript-eslint/no-use-before-define": [
          "warn",
          {
            "functions": false,
            "classes": false,
            "variables": false,
            "typedefs": false
          }
        ],
        "no-unused-vars": "off",
        "@typescript-eslint/no-unused-vars": [
          "error",
          {
            "args": "none",
            "ignoreRestSiblings": true
          }
        ],
        "no-useless-constructor": "off",
        "@typescript-eslint/no-useless-constructor": "warn",
        "import/extensions": 0,
        "import/no-unresolved": 0
      }
    }
  ],
  "parserOptions": {
    "ecmaFeatures": {
      "legacyDecorators": 1
    }
  }
}

至此, 對 ESlint 的配置已經(jīng)完成

提交代碼時自動檢查

我們使用 git 進(jìn)行版本控制
利用 husky + lint-staged 可以進(jìn)行代碼質(zhì)量的自動化檢測

執(zhí)行

yarn add -D husky lint-staged pretty-quick cross-env

安裝相關(guān)依賴

package.json 中添加相關(guān)配置

  "scripts": {
    "lint": "cross-env LINT=1 eslint --ext .js,.ts assets"
  },
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
  "lint-staged": {
    "*.{js,jsx,ts,tsx}": [
      "cross-env LINT=1 eslint --fix",
      "pretty-quick --staged",
      "git add"
    ]
  }

檢驗配置

打開 assets/Script/Helloworld.ts
寫下 let test = 1;

GIF.gif

不出意外的話保存文件會自動修復(fù) let 聲明未變動量, 還有一個未使用變量的錯誤無法自動修復(fù), 此時在根目錄執(zhí)行

yarn lint

檢查代碼

會報

C:\projectpath\assets\Script\Helloworld.ts
  14:11  error  'test' is assigned a value but never used  @typescript-eslint/no-unused-vars

? 1 problem (1 error, 0 warnings)

error Command failed with exit code 1.

ESlint 檢出了這個錯誤

此時執(zhí)行

git add .
git commit -m 'lint test'

也會報錯并阻止你本次提交, 說明配置成功
根據(jù)報錯提示修改代碼后提交才能成功

至此, cocos creator + typescript + ESlint + Prettier 的團(tuán)隊代碼檢測一條龍配置完成

其他配置(可選)

為了進(jìn)一步保證團(tuán)隊環(huán)境一致和代碼整潔, 還有如下配置文件可以選擇性添加

.gitattributes 提交時統(tǒng)一使用 lf 換行

* text=auto eol=lf

.nvmrc nvm NodeJS 版本限制, 配合下面的 engine 配置使用

v10.16.2

package.json 添加如下配置

  "engines": {
    "node": "^10.0.0"
  }

統(tǒng)一控制團(tuán)隊 NodeJS 版本

.yarnclean 每次安裝完模塊后清除 node_modules 內(nèi)多余的配置, 測試,說明等不必要文件縮小項目體積

# test directories
__tests__
test
tests
powered-test

# asset directories
docs
doc
website
images

# examples
example
examples

# code coverage directories
coverage
.nyc_output

# build scripts
Makefile
Gulpfile.js
Gruntfile.js

# configs
appveyor.yml
circle.yml
codeship-services.yml
codeship-steps.yml
wercker.yml
.tern-project
.gitattributes
.editorconfig
.*ignore
.eslintrc
.jshintrc
.flowconfig
.documentup.json
.yarn-metadata.json
.travis.yml

# misc
*.md

代價是安裝時多花費一點時間, 反正是自動的

進(jìn)階

再在最后講一下使用 lerna 進(jìn)行 monorepo 包管理

代碼寫多了以后, 經(jīng)常想封裝成模塊以復(fù)用, 使用 lerna 可以方便地管理多個包及其之間的依賴關(guān)系

太長了, 算了, 再說吧

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容