用eslint、pritter統一代碼風格


什么是 eslint

限制代碼的規則,進而使項目代碼風格保持統一

作用

1. 代碼格式錯誤、簡單錯誤的提醒
2. 修復上述錯誤

eslint 的用法

安裝 eslint

安裝 eslint npm 包

生成規則

安裝 eslint 包后,我們可以使用 npx 命令來調用 eslint 包的腳本了。
我們在更目錄下新建一個文件:error.js

// error.js
console.log(a);

讓我們來試試剛剛安裝的 eslint 包是否起作用
命令行:./node_modules/.bin/eslint error.js

馬上我們會得到這樣的一個提示:

➜  eslint ./node_modules/.bin/eslint error.js

Oops! Something went wrong! :(

ESLint: 6.5.1.

ESLint couldn't find a configuration file. To set up a configuration file for this project, please run:

    eslint --init

ESLint looked for configuration files in /Users/senguo 1/huang/eslint and its ancestors. If it found none, it then looked in your home directory.

If you think you already have a configuration file or if you need more help, please stop by the ESLint chat room: https://gitter.im/eslint/eslint

或者,我們也可以這樣。命令行:npx eslint error.js

馬上我們會得到這樣的一個提示:

➜  eslint npx eslint error.js
No ESLint configuration found in /Users/senguo 1/huang/eslint.

上面的提示告訴我們,eslint 需要找到配置文件才能工作。
並提示我們運行命令:eslint --init (我並沒有全局安裝,並且我建議選擇局部安裝)

所以我們用下面的命令代替上面的命令:
npx eslint --init
來創建一個配置文件。

我選擇了 vue 框架。
不幸的是,配置文件生成失敗了.

➜  eslint npx eslint --init
? How would you like to use ESLint? To check syntax, find problems, and enforce code style
? What type of modules does your project use? CommonJS (require/exports)
? Which framework does your project use? Vue.js
? Does your project use TypeScript? No
? Where does your code run? (Press <space> to select, <a> to toggle all, <i> to invert selection)Browser
? How would you like to define a style for your project? Answer questions about your style
? What format do you want your config file to be in? JavaScript
? What style of indentation do you use? Spaces
? What quotes do you use for strings? Single
? What line endings do you use? Unix
? Do you require semicolons? No
Local ESLint installation not found.
The config that you've selected requires the following dependencies:

eslint-plugin-vue@latest eslint@latest
An error occurred while generating your JavaScript config file. A config file was still generated, but the config file itself may not follow your linting rules.
Error: Failed to load plugin 'vue' declared in 'BaseConfig': Cannot find module 'eslint/lib/rules/array-bracket-spacing'
Referenced from: BaseConfig
Error: An error occurred while generating your JavaScript config file. A config file was still generated, but the config file itself may not follow your linting rules.
Error: Failed to load plugin 'vue' declared in 'BaseConfig': Cannot find module 'eslint/lib/rules/array-bracket-spacing'
Referenced from: BaseConfig
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)
    at Function.Module._load (internal/modules/cjs/loader.js:562:25)
    at Module.require (internal/modules/cjs/loader.js:690:17)
    at require (/Users/senguo 1/huang/eslint/node_modules/v8-compile-cache/v8-compile-cache.js:161:20)
    at Object.<anonymous> (/Users/senguo 1/node_modules/eslint-plugin-vue/lib/rules/array-bracket-spacing.js:9:31)
    at Module._compile (/Users/senguo 1/huang/eslint/node_modules/v8-compile-cache/v8-compile-cache.js:194:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
➜  eslint

根據錯誤提示,我們安裝依賴:

➜  eslint yarn add eslint-plugin-vue@latest eslint@latest

再次運行命令:
npx eslint --init

這次成功了!

➜  eslint npx eslint --init
? How would you like to use ESLint? To check syntax, find problems, and enforce code style
? What type of modules does your project use? CommonJS (require/exports)
? Which framework does your project use? Vue.js
? Does your project use TypeScript? No
? Where does your code run? (Press <space> to select, <a> to toggle all, <i> to invert selection)Browser
? How would you like to define a style for your project? Answer questions about your style
? What format do you want your config file to be in? JavaScript
? What style of indentation do you use? Spaces
? What quotes do you use for strings? Single
? What line endings do you use? Unix
? Do you require semicolons? No
Local ESLint installation not found.
The config that you've selected requires the following dependencies:

eslint-plugin-vue@latest eslint@latest
Successfully created .eslintrc.js file in /Users/senguo 1/huang/eslint
ESLint was installed locally. We recommend using this local copy instead of your globally-installed copy.
➜  eslint

我們可以看到在項目更目錄多了一個文件,名為.eslintrc.js(后綴名是上面問答中的一個選項)。推薦.js后綴,因為json格式不支持代碼注釋,並且在需要根據環境變量來做不同情況處理時十分無力。

module.exports = {
  env: {
    browser: true,
    commonjs: true,
    es6: true
  },
  extends: ["eslint:recommended", "plugin:vue/essential"],
  globals: {
    Atomics: "readonly",
    SharedArrayBuffer: "readonly"
  },
  parserOptions: {
    ecmaVersion: 2018
  },
  plugins: ["vue"],
  rules: {
    indent: ["error", 4],
    "linebreak-style": ["error", "unix"],
    quotes: ["error", "single"],
    semi: ["error", "never"]
  }
};

檢測代碼

現在,激動人心的時刻終於到來了。

我們要對代碼進行檢測了!

命令行輸入:
npx eslint error.js

➜  eslint npx eslint error.js

/Users/senguo 1/huang/eslint/error.js
  1:13  error  'a' is not defined  no-undef

✖ 1 problem (1 error, 0 warnings)

➜  eslint

看,檢測成功了!

我們來看一下提示的含義。

/Users/senguo 1/huang/eslint/error.js
表示當前檢測的是哪一個文件

1:13 error 'a' is not defined no-undef

1. `1:13` 表示錯誤出現在第1行的第13列
2. `error  'a' is not defined` 表示為什么會出錯
3. `no-undef` 這是一個規則代號,我們可以在配置文件中配置這一類型的錯誤,讓這個錯誤變成*警告*級別,或者關閉它

修復代碼

當我們發現錯誤,很常見的情況是,我們馬上就要修復它!

當我們的文件很多的時候,這常常會花費很多時間。現在我們可以用 eslint 來解決。

現在立刻遇到了一個新的問題:修復代碼的命令是什么?

一般,npm 包在運行名字但不帶任何參數的情況下,會告訴你該包的用法。
命令行:npx eslint

➜  eslint npx eslint
eslint [options] file.js [file.js] [dir]

Basic configuration:
  --no-eslintrc                  Disable use of configuration from .eslintrc.*
  -c, --config path::String      Use this configuration, overriding .eslintrc.* config options if present
  --env [String]                 Specify environments
  --ext [String]                 Specify JavaScript file extensions - default: .js
  --global [String]              Define global variables
  --parser String                Specify the parser to be used
  --parser-options Object        Specify parser options
  --resolve-plugins-relative-to path::String  A folder where plugins should be resolved from, CWD by default

Specifying rules and plugins:
  --rulesdir [path::String]      Use additional rules from this directory
  --plugin [String]              Specify plugins
  --rule Object                  Specify rules

Fixing problems:
  --fix                          Automatically fix problems
  --fix-dry-run                  Automatically fix problems without saving the changes to the file system
  --fix-type Array               Specify the types of fixes to apply (problem, suggestion, layout)

Ignoring files:
  --ignore-path path::String     Specify path of ignore file
  --no-ignore                    Disable use of ignore files and patterns
  --ignore-pattern [String]      Pattern of files to ignore (in addition to those in .eslintignore)

Using stdin:
  --stdin                        Lint code provided on <STDIN> - default: false
  --stdin-filename String        Specify filename to process STDIN as

Handling warnings:
  --quiet                        Report errors only - default: false
  --max-warnings Int             Number of warnings to trigger nonzero exit code - default: -1

Output:
  -o, --output-file path::String  Specify file to write report to
  -f, --format String            Use a specific output format - default: stylish
  --color, --no-color            Force enabling/disabling of color

Inline configuration comments:
  --no-inline-config             Prevent comments from changing config or rules
  --report-unused-disable-directives  Adds reported errors for unused eslint-disable directives

Caching:
  --cache                        Only check changed files - default: false
  --cache-file path::String      Path to the cache file. Deprecated: use --cache-location - default: .eslintcache
  --cache-location path::String  Path to the cache file or directory

Miscellaneous:
  --init                         Run config initialization wizard - default: false
  --env-info                     Output execution environment information - default: false
  --debug                        Output debugging information
  -h, --help                     Show help
  -v, --version                  Output the version number
  --print-config path::String    Print the configuration for the given file
➜  eslint

我們找到有這么一句

Fixing problems:
  --fix                          Automatically fix problems

我們現在嘗試修復代碼:
npx eslint --fix error.js

發現了什么?沒有任何改變!但這的確是一個有問題的文件,為什么 eslint 沒有修復它呢?
因為這樣的錯誤 eslint 不知道如何修復

現在,我們來修改一下error.js文件

console.log(a);
function greeting() {
  alert("hello");
}

運行命令:npx eslint --fix error.js
我們可以看到error.js文件發生了變化

console.log(a);
function greeting() {
  alert("hello");
}

eslint 會告訴你風格和代碼的錯誤,但是只會幫你修復風格的錯誤

關於更多腳本

eslint 有很多命令,他可以批量發現/修復文件

解讀 eslint 配置文件

module.exports = {
  env: {
    browser: true,
    commonjs: true,
    es6: true
  },
  extends: ["eslint:recommended", "plugin:vue/essential"],
  globals: {
    Atomics: "readonly",
    SharedArrayBuffer: "readonly"
  },
  parserOptions: {
    ecmaVersion: 2018
  },
  plugins: ["vue"],
  rules: {
    indent: ["error", 4],
    "linebreak-style": ["error", "unix"],
    quotes: ["error", "single"],
    semi: ["error", "never"]
  }
};


免責聲明!

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



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