🏿 前言
我们创建vue项目时,通常会涉及到选择代码检测和格式化方案,该如何挑选适合自己的个性化配置?本文就来谈谈 ESLint 各个模式的编码规范,以便大家根据自身情况进行选取。
选择Linter / Formatter配置:
选项:
ESLint with error prevention only // 仅错误预防
ESLint + Airbnb config // Airbnb配置
ESLint + Standard config // 标准配置
ESLint + Prettier // 附带Prettier
应用了 ESLint 后,通常是需要自己来配置繁杂的 rules 规则。这也是一个喜好类的东西,多数人是不愿意在这上面耗费太多精力的,比如手动配置数百个ESLint 规则。
于是github 上出现了一些开源的代码规范库,比较流行的有 airbnb、standard、prettier等。相比之下大家都推荐Prettier预设规范,配置更少,用起来更舒服。
来看看不同的模式的选择,进而生成不同的配置文件.eslintrc.js
🏿 不同模式的.eslintrc.js文件配置
仅错误预防
只检测错误
module.exports = {
root: true,
env: {
node: true
},
'extends': [
'plugin:vue/vue3-essential',
'eslint:recommended',
'@vue/typescript/recommended'
],
parserOptions: {
ecmaVersion: 2020
},
rules: {
'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off'
}
}
Standard风格
生成Standard编码规范
module.exports = {
root: true,
env: {
node: true
},
extends: [
'plugin:vue/vue3-essential',
'@vue/standard',
'@vue/typescript/recommended'
],
parserOptions: {
ecmaVersion: 2020
},
rules: {
'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off'
}
}
Prettier 风格
生成Prettier 编码规范
module.exports = {
root: true,
env: {
node: true,
},
extends: [
"plugin:vue/vue3-essential",
"eslint:recommended",
"@vue/typescript/recommended",
"plugin:prettier/recommended",
],
parserOptions: {
ecmaVersion: 2020,
},
rules: {
"no-console": process.env.NODE_ENV === "production" ? "warn" : "off",
"no-debugger": process.env.NODE_ENV === "production" ? "warn" : "off",
},
};
Airbnb风格
独角兽公司 Airbnb 的前端编码规范
选择何时进行代码检测
Pick additional lint features:
Lint on save // 保存就检测
Lint and fix on commit // fix和commit时候检查
🏿 参考
使用 Eslint & standard 规范前端代码:https://www.cnblogs.com/zhoumingjie/p/11582862.html
各种lint预设pk:eslint-config-airbnb vs prettier vs standard | npm trends
为什么推荐使用prettier:Vue3中eslint代码格式化prettier和standard规则比较
我为什么推荐Prettier来统一代码风格:我为什么推荐Prettier来统一代码风格
Vue CLI 3.0 文档:Vue CLI 3.0 文档(1):安装和项目创建 | 蓝色梦想
ESLint 与 Prettier配合使用:javascript - 使用ESLint+Prettier来统一前端代码风格