前言
原文地址(强烈建议看原文):https://www.jianshu.com/p/5b7296445a0e
eslint官网地址:https://eslint.bootcss.com/docs/user-guide/getting-started
目录:
- 插件安装
- 插件简介
- 实战演练
- 文件介绍
- 补充文件
- eslint.js配置
- 关闭eslint
- 附录官网
一. 插件安装
1.sublime text 3 配置和使用eslint:https://blog.csdn.net/WU5229485/article/details/85325730
2.vscode配置和使用eslint:
vscode插件中搜索eslint和prettier安装插件。
啥也不管,这俩必须得装。
二. 插件简介
vscode插件库里的eslint是用来在你写代码的时候就直接给你报错。(vue-cli中的eslint是在浏览器中报错)
prettier是代码格式化插件,用来辅助eslint,否则你调了花半天,一格式化全没有。
在实战前可能需要安装ESLint,可以先不安装等报错了在安装ESLint
你可以使用 npm 安装 ESLint:
$ npm install eslint --save-dev
三. 实战演练
# 创建一个vue项目 [email protected],更高版本请使用create创建项目。
vue init webpack eslint_test
eslint那一栏请选择none,这样vue-cli会帮你下载eslint,并进行一些基本的配置。
但是不会帮你设置rules(rules就是各种代码规范的不允许)。
下载好后目录结构如下:
四. 文件介绍
里面有两个文件非常重要。
.eslintignore 和 .eslintrc.js
.eslintignore ,见名知意,ignore 忽视一些文件。即在文件里面规定的不会被eslint进行检查。
例如这里面不会对/build/文件下面的文件做语法检查。
.eslintrc.js ,是eslint能起作用的根本。 vue-cli里面eslint和 vscode里的eslint都以这个文件为判定标准。
五. 补充文件
我们得在根目录下新建一个.prettierrc文件。
.prettierrc,是prettier格式化的配置文件,建议用json格式书写。
例如你如果配置下面样式。
{
// 采用分号
"semi": true,
// 采用单引号
"singleQuote": true,
// tab采用两个空格长度
"tabWidth": 2
}
格式化过程就会像下图所示:
双引号自动改成单引号,没加的分号,自动补齐。
六. eslint.js配置
上文中说过,.eslintrc.js是eslint起作用的关键文件,所以我们必须学会进行一些配置。
如果安装eslint的时候选择none,.eslintrc.js文件应该和下面是一样的。
// https://eslint.org/docs/user-guide/configuring
module.exports = {
root: true,
parserOptions: {
parser: 'babel-eslint'
},
env: {
browser: true,
},
// https://github.com/vuejs/eslint-plugin-vue#priority-a-essential-error-prevention
// consider switching to `plugin:vue/strongly-recommended` or `plugin:vue/recommended` for stricter rules.
extends: ['plugin:vue/essential'],
// required to lint *.vue files
plugins: [
'vue'
],
// add your custom rules here
rules: {
// allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off'
}
}
上面最重要的模块就是rules模块。它是给我们来设定一些eslint的规则的。
例如我在rules里面添加一条规则'no-var': ['error'],此时我们就不能在程序中使用var来定义变量了。
只能使用let来定义变量,const来定义常量。
rules: {
// allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
'no-var': ['error'],
},
例如下图中,我写了var a = 1;它直接报错了。
其他的也与之类似。附常用rule:
rules: {
// allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
// 尾随逗号规则
'comma-dangle': [
'error',
{
arrays: 'always',
objects: 'always',
imports: 'never',
exports: 'never',
functions: 'never',
},
],
// 禁止使用var规则
'no-var': ['error'],
// 必须使用分号
semi: ['error', 'always'],
// 必须使用单引号
quotes: ['error', 'single'],
// 必须使用两个空格进行缩进
indent: ['error', 2],
},
七. 关闭eslint
参考vue-cli2创建项目过程的详细解析及项目目录解析中方式一和方式三的比较
如:
https://jingyan.baidu.com/article/ab0b563046106bc15afa7de2.html
八. 附录官网
prettier官网 https://prettier.io/docs/en/configuration.html
eslint官网 https://eslint.bootcss.com/docs/rules/
airbnb中文文档 https://github.com/BingKui/javascript-zh#functions