写在前面: 本教程为有一定代码规范的开发者提供。如果您是新手,建议严格按照规范矫正自己的代码风格。尽量在没有ESLint的情况下也能写出漂亮规范的代码
您是否还在为ESLint的语法校验规则而头疼?
您是否还饱受ESLint的语法规则的折磨?
您是否还在手动修改ESLint的错误?
别着急,这篇文章将彻底让你告别ESLint所带来的各种困扰。(视频以Vue-js录制,适用于anglar中的ts)
先上效果:
自动校验ESLint
准备工作:
npm install eslint --save-dev
npm install --save-dev --save-exact prettier
5.在项目根目录创建.eslint.json、.prettier.json文件或.eslintre.js、.prettierrc.js文件
.prettierrc.js写入校验规则,具体自行百度
module.exports = {
printWidth: 200,
tabWidth: 2,
useTabs: false,
semi: false, //
singleQuote: true, //
quoteProps: 'as-needed',
trailingComma: 'none', // for better git history
bracketSpacing: true,
arrowParens: 'avoid', // avoid (default): Omit parens when possible. Example: x => x
htmlWhitespaceSensitivity: 'ignore', // for better format
endOfLine: 'lf', // windows users: git config core.autocrlf false --global
// eslintIntegration: 'true',
}
.eslintrc.js写入配置,具体自行百度
module.exports = {
root: true,
env: {
browser: true,
node: true,
},
parserOptions: {
parser: 'babel-eslint',
},
extends: [
'@nuxtjs',
'prettier',
'prettier/vue',
'plugin:prettier/recommended',
'plugin:nuxt/recommended',
],
plugins: ['prettier'],
rules: {
'camelcase': 'off',
'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
},
globals: {
WxLogin: true,
},
}
{
"editor.defaultFormatter": "SimonSiefke.prettier-vscode",
// 缩进字符 2
"editor.tabSize": 2,
"editor.suggestSelection": "first",
"vsintellicode.modify.editor.suggestSelection": "automaticallyOverrodeDefaultValue",
"java.semanticHighlighting.enabled": true,
"window.zoomLevel": 0,
// #去掉代码结尾的分号
"prettier.semi": true,
// 让prettier使用eslint的代码格式进行校验
"prettier.eslintIntegration": true,
// 使用单引号替代双引号
"prettier.singleQuote": true,
// 函数名和后面的括号之间加个空格
"javascript.format.insertSpaceBeforeFunctionParenthesis": true,
// 每次保存自动格式化
"editor.formatOnSave": true,
// eslint格式化字符串
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true,
// "eslint.autoFixOnSave": false,
"source.fixAll.tslint": false
},
"eslint.codeAction.disableRuleComment": {
},
"editor.fontLigatures": false,
"explorer.confirmDelete": false,
"java.configuration.checkProjectSettingsExclusions": false,
// tslint配置
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"javascript.updateImportsOnFileMove.enabled": "always",
"editor.rulers": [
]
}
最后一步,非常重要!!!
很多开发配置完上述内容后发现并没有生效,或者没有完全生效。这里要注意,vscode右下角有两个按钮,注意其状态,一定要钩上
至此,当我们保存后,代码就会自动根据ESLint的校验规则进行自动修复。再也不需要手动修改了,效率大大提升~~~~