配置ESLint有利于保证JS代码的规范性,并能避免一些低级的代码错误,对于团队开发大有裨益。以下以Vue项目中的ESlint为例,详细给大家介绍其使用方法。
一、安装
安装命令
//开发环境中安装依赖
//npm
npm i ESlint -D
//yarn
yarn add --dev ESlint
二、文件准备
创建 ESlint 所需文件
在根目录下创建.eslintrc.js配置文件及.eslintignore忽略文件
三、创建配置
1. 创建格式化参考规则
在.eslintrc.js中写入以下内容:
module.exports = {
env: {//指定解析环境
browser: true,
node: true,
commonjs: true,
},
extends: [////规则扩展,部分扩展需要单独下载
'eslint:recommended',
'plugin:vue/recommended',
'plugin:prettier/recommended', //避免与 prettier 冲突
],
parserOptions: {//指定解析方式
ecmaVersion: 2021,
sourceType: 'module',
ecmaFeatures: {
jsx: true,
},
},
rules: {
//rules中的2代表警告,1代表更为严格的抛出错误
'no-await-in-loop': 2,//循环中不能出现await
'no-console': 1,//
'no-debugger': 1,
'no-func-assign': 0,
'no-template-curly-in-string': 1, //常规字符串中禁止使用模板字符串方法
'default-case': 1, //switch中必须具有default
'no-alert': 2,
'vue/attribute-hyphenation': [2, 'never'], //自定义组件中的属性应为小驼峰命名,除data-之类的之外
'vue/component-definition-name-casing': [2, 'PascalCase'], //vue script自定义组件的name应为大驼峰形式
'vue/component-name-in-template-casing': [2, 'kebab-case'], //vue html中的组件应为连字符形式
'vue/html-quotes': [2, 'double'], //vueHTml中使用单引号
'vue/prop-name-casing': [2, 'camelCase'], //自定义属性使用小驼峰
'vue/attributes-order': [
1,
{
order: [
'DEFINITION',
'LIST_RENDERING',
'CONDITIONALS',
'RENDER_MODIFIERS',
'GLOBAL',
['UNIQUE', 'SLOT'],
'TWO_WAY_BINDING',
'OTHER_DIRECTIVES',
'OTHER_ATTR',
'EVENTS',
'CONTENT',
],
alphabetical: false,
},
], //vue-html中的属性顺序
'vue/component-tags-order': [
2,
{
order: [['template', 'script'], 'style'],
},
], //vue中的标签顺序
'vue/order-in-components': [
1,
{
order: [
'el',
'name',
'key',
'parent',
'functional',
['delimiters', 'comments'],
['components', 'directives', 'filters'],
'extends',
'mixins',
['provide', 'inject'],
'ROUTER_GUARDS',
'layout',
'middleware',
'validate',
'scrollToTop',
'transition',
'loading',
'inheritAttrs',
'model',
['props', 'propsData'],
'emits',
'setup',
'asyncData',
'data',
'fetch',
'head',
'computed',
'watch',
'watchQuery',
'LIFECYCLE_HOOKS',
'methods',
['template', 'render'],
'renderError',
],
},
], //vue-script中的属性顺序
'vue/this-in-template': 2, //vue-html中不允许存在this
},
};
eslint:recommended 插件中其实包含了很多的规则,详见官网
2. 配置忽略文件
在.eslintignore中写入以下内容:
// 忽略如下文件夹(主要为静态资源、打包后的文件)
build
src/assets
public
dist
四、格式化文档
1. 命令行格式化检测并修复指定文档
eslint --fix src/components/HelloWorld.js
2. 利用编辑器插件进行格式化
(1) 在VS Code中搜索相应的 eslint 扩展安装。
(2) 打开VS Code配置文件setting.json,在其中添加以下内容:
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true,
},
如此便可在编辑器保存文件时执行Eslint检测并修复。
3. 集成在 git 生命周期中
利用 Husky 集中在'pre-commit'生命周期,即可在每次提交前检查代码。
-----正文完----- 相关文章推荐: 《前端团队开发思考》