ESlint的使用


官方網站

eslint 官網
eslint-plugin-prettier 官網
lint-staged 官網
prettier 官網

安裝

npm install eslint --save-dev

配合 prettier 安裝

npm install eslint eslint-config-prettier eslint-plugin-prettier prettier --save-dev

初始化配置

./node_modules/.bin/eslint --init

或者

npx eslint --init

根據提示進行配置

$ npx eslint --init
You can also run this command directly using 'npm init @eslint/config'.
√ How would you like to use ESLint? · style
√ What type of modules does your project use? · none
√ Which framework does your project use? · none
√ Does your project use TypeScript? · No / Yes
√ Where does your code run? · browser
√ How would you like to define a style for your project? · prompt
√ What format do you want your config file to be in? · JavaScript
√ What style of indentation do you use? · tab
√ What quotes do you use for strings? · double
√ What line endings do you use? · unix
√ Do you require semicolons? · No / Yes
A config file was generated, but the config file itself may not follow your linting rules.
Successfully created .eslintrc.js file in C:\ls-project03\miniprogr

運行 eslint --init 之后,.eslintrc 文件會在你的文件夾中自動創建

配合 prettier 的配置

module.exports = {
  env: {
    browser: true,
    es2021: true,
  },
  // 添加 prettier 預設配置
 + extends: ["plugin:prettier/recommended"],
  parserOptions: {
    ecmaVersion: "latest",
    sourceType: "module",
  },
  rules: {
  // prettier 錯誤變為警告
  +  "prettier/prettier": ["warn"],
  },
};

設置排除文件

.eslintignore

項目目錄添加.eslintignore 文件,添加需要 eslint 排除的文件 默認排除 node_modules

node_modules

.prettierignore

項目目錄添加.prettierignore 文件,添加需要 prettier 排除的文件 tip:prettier 默認排除 node_modules

node_modules

添加 npm 腳本

package.json

  "scripts": {
   + "lint": "prettier --write .",
   + "lint:js": "eslint --fix .",
  },

prettier --write . 修復項目目錄下所有文件,``.prettierignore 會被排除

eslint --fix . 修復項目目錄下所有 js 文件,``.eslintignore 會被排除

設置 commit 時自動 lint

安裝 husky 和 lint-staged 並自動配置

npx mrm@2 lint-staged

修改 package.json

"lint-staged": {
   - "*.js": "eslint --cache --fix",
   // 使用 prettier 進行 lint
   +"*": "prettier --ignore-unknown --write"
  }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM