配置ESLint有利於保證JS代碼的規範性,並能避免一些低級的代碼錯誤,對於團隊開發大有裨益。如下以Vue項目中的ESlint爲例,詳細給你們介紹其使用方法。html
//開發環境中安裝依賴
//npm
npm i ESlint -D
//yarn
yarn add --dev ESlint
複製代碼
在根目錄下建立.eslintrc.js
配置文件及.eslintignore
忽略文件前端
在.eslintrc.js
中寫入如下內容:vue
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 插件中其實包含了不少的規則,詳見官網node
在.eslintignore
中寫入如下內容:git
// 忽略以下文件夾(主要爲靜態資源、打包後的文件)
build
src/assets
public
dist
複製代碼
eslint --fix src/components/HelloWorld.js
複製代碼
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true,
},
複製代碼
如此即可在編輯器保存文件時執行Eslint檢測並修復。npm
利用 Husky 集中在'pre-commit'生命週期,便可在每次提交前檢查代碼。json
-----正文完----- 相關文章推薦:bash
《前端團隊開發思考》markdown
《Prettier配置指南》curl