用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"]
  }
};
posted @ 2019-10-23 16:49  菜鸡_chicken  阅读(3696)  评论(0编辑  收藏  举报