1. vscode 下载插件 eslint
2.下载node
下载安装之后,全局安装eslint
npm i eslint -g
eslint -v
有版本号为安装成功
3.配置VsCode setting.json
可以 Ctrl+, 或者
// 启用Eslint
"eslint.enable": true,
// 保存时自动格式化代码
"editor.codeActionsOnSave": {
"source.fixAll": false,
"source.fixAll.eslint": true
},
3.配置eslint
两种配置:当前项目配置(只检查当前项目)和全局配置(检查所有用vscode打开的js,html …)
- 当前项目配置 ,先进入项目根目录
npm init -y //-y为忽略问答,直接创建pack.json
eslint --init //初始化
? How would you like to use ESLint?
To check syntax only // 只检查语法
> To check syntax and find problems // 检查语法并发现问题
To check syntax, find problems, and enforce code style // 检查语法、发现问题并强制执行代码样式
? What type of modules does your project use?
> JavaScript modules (import/export)
CommonJS (require/exports)
None of these
? Which framework does your project use?
React
Vue.js
> None of these
? Does your project use TypeScript? » *No* / Yes
? Where does your code run? ... (Press <space> to select, <a> to toggle all, <i> to invert selection)
√ Browser
√ Node
? What format do you want your config file to be in? ...
> JavaScript
YAML
JSON
? Would you like to install them now with npm? » No / **Yes**
然后打开自动生成的eslintrc 配置文件
简单配置下,具体规则 Eslint 官网查看
"rules": {
// 以分号结
"semi": "error",
// 空行
"no-multiple-empty-lines": [
"error",
{
"max": 1 // 最多1行空行
}
]
}
优化下
npm i babel-eslint --save-dev// 配置eslint解析器,建议使用这个,比默认的强大,不配置也能用
在 .eslintrc.js 中:
"parser": "babel-eslint",
再来个检测html
npm i eslint-plugin-html --save-dev // 此插件用来识别.html 和 .vue文件中的js代码
在 .eslintrc.js 中:
"plugins": [
"html" // 此插件用来识别.html 和 .vue文件中的js代码
],
或者vscode setting.json 配置启用html 检查
"eslint.options": {
"plugins": [
"html" // 此插件用来识别.html 和 .vue文件中的js代码
],
},
2. 全局配置
npm i eslint -g
npm i babel-eslint -g
npm i eslint-plugin-html -g
获取下 npm root 的全局路径
npm root -g
C:\Users\[your name]\AppData\Roaming\npm\node_modules
// 注意是你的路径,中括号中应该是你的用户名
cd C:\Users\[your name]\AppData\Roaming\npm
start .
然后在这个文件夹下创建 .eslintrc.js
随便配置下:
module.exports = {
"env": {
"browser": true,
"es2020": true,
"node": true
},
"extends": "eslint:recommended",
"parserOptions": {
"ecmaVersion": 11,
"sourceType": "script"
},
"parser": "babel-eslint",
"plugins": [
"html" // 此插件用来识别.html 和 .vue文件中的js代码
],
"root": true,
"rules": {
// 分号
"semi": 2,
// 空行
"no-multiple-empty-lines": [
"error",
{
"max": 1 // 最多1行空行
}
]
}
};
在VsCode Setting.json 中:
"eslint.options": {
// 注意填你自己的路径
"configFile": "C:\\Users\\[Your Name]\\AppData\\Roaming\\npm\\.eslintrc.js",
},