前端自动化规范工具 eslint检查语法
实现功能
- vs code 提示代码错误
- vs code 在保存的时候自动修复错误代码或不符合规范的代码
安装
全局和相项目安装eslint
$npm install -g eslint
$npm install --save-dev eslint
生成配置
初始化eslint配置
$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
第三步 选择是否支持Typescript
? 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
这时候会在项目目录生成.eslintrc.json
步骤三
eslint会默认引入标准规范recommended
自定义配置参考:ESLint - 插件化的 JavaScript 代码检测工具 - ESLint中文文档 (bootcss.com)
自定义配置写在根节点rules中例如
第一个参数:
"off
"或0-关闭规则
"warn
"或1-将该规则作为警告打开(不影响退出代码)
"error
"或2-将规则作为错误打开(退出代码将为1)
第二个参数
always
(默认):需要
never
:不允许
{
"env": {
"browser": true,
"es2021": true,
"node": true
},
"extends": "eslint:recommended",
"parserOptions": {
"ecmaVersion": "latest"
},
"rules": {
"no-var":"error", //禁止使用var
"quotes":["error", "single"], //使用单引号
"semi":"error" //末尾;
}
}
步骤四
**使用命令行修复代码 **
$eslint --fix xxx.js
**vs code 配置保存自动修复代码 **
- vs code安装
eslint
插件 - 在vs code settings.json加入以下配置可以实现保存的时候自动修复错误语法
"editor.codeActionsOnSave": {
"source.fixAll": true
}