0%

在VSCode里配置 ESLint + Airbnb + Vue

前言:在网上找了一圈后没找到完整且最新的配置方案,故整合了几个优质答案和自己的心得,写了这篇文章。

PS:参考文章在文章底部列出,如有侵权,请联系我删除,谢谢。

创建 VUE 项目

1
2
3
4
5
6
7
8
9
10
vue init webpack      //  初始化安装VUE项目
project name // 输入项目名称
project description // 输入项目说明
author // 输入作者
Vue build // 运行环境
Install vue-router
Use ESLint to lint your code (Yes/No) //选择YES,安装eslint插件
(选择代码规范airbnb)
Set up unit tests (Y/N)
....

安装 ESLint

在 VSCode 中安装 ESLint 扩展

打开 VSCode 搜索 ESLint 扩展安装

用 NPM 安装 ESLint 包

  1. 全局安装(推荐):

    npm install eslint -g

  2. 项目根目录本地安装:

    npm install eslint --save-dev

采用 Airbnb 的代码规范

安装相关插件

npm install eslint-config-airbnb-base eslint-plugin-import babel-eslint -g

修改配置文件 .eslintrc.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
module.exports = {
root: true,
// 要启用的环境
env: {
// 添加browser和es6的环境
browser: true,
es6: true,
node: true
},
// 关键:启用 airbnb 规则
extends: ['plugin:vue/essential', 'airbnb-base'],
// 使用语言及版本
parserOptions: {
parser: 'babel-eslint',
ecmaVersion: 2017,
sourceType: 'module'
},
// 个人自定义规则
rules: {
'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off'
}
}

设置 Vscode 的 eslint 插件

  1. 安装 eslint-plugin-vue 插件
1
npm i -g eslint-plugin-vue
  1. 在 VSCode 的设置文件(settings.json)中添加如下配置:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
"eslint.enable": true,
// 保存时是否自动修复
"eslint.autoFixOnSave": true,
"eslint.alwaysShowStatus": true,
"eslint.provideLintTask": true,
"eslint.options": {
// 配置文件的地址
// 请将下面的地址换成你的eslint配置文件.eslintrc.js的地址!!!
"configFile": "/Users/young/Desktop/music-player-in-Vue/.eslintrc.js",
},
"eslint.validate": [
"javascript",
"javascriptreact",
// 启用 html 和 vue 中 ESLint 验证和自动修复
{
"language": "html",
"autoFix": true
},
{
"language": "vue",
"autoFix": true
}
]

参考文章

  1. VSCode 配置 ESLint + Airbnb + Vue
  2. Vue 项目中使用 eslint 的笔录,编辑器采用 sublime3