配置篇分上中下三部分,本篇主要介绍eslint+prettier
一、安装vscode插件 eslint
二、安装依赖:eslint
、eslint-plugin-vue
pnpm i eslint eslint-plugin-vue -D
三、在项目根路径下新建文件 .eslintrc.js
.eslintrc.js
module.exports = {
root: true,
extends: ['plugin:vue/vue3-recommended'],
rules: {
'vue/valid-template-root': 'off',
'vue/no-multiple-template-root': 'off',
'vue/multi-word-component-names': [
'error',
{
ignores: ['index'],
},
],
},
}
点开 App.vue
会看到出现了很多警告或者错误,说明eslint已经生效了
但是如果要让我们一个个去修复这些警告或者错误那就太麻烦了,有没有办法找出所有的警告并且修复呢,答案肯定是有的
四、在 package.json
文件添加两个npm执行指令
package.json
scripts: {
...
"lint": "eslint --ext .js,.vue .",
"lint:fix": "eslint --fix --ext .js,.vue .",
}
执行 pnpm run lint
会在控制台列出所有的eslint警告项和错误项
执行 pnpm run lint:fix
则可以将所有的eslint警告项和错误项自动修复(仅限于代码风格类的错误和警告)
但是还是感觉不够爽,每次要修复的时候还得去执行指令,可不可以保存的时候进行自动修复呢?
五、在.vscode目录下新建 settings.json
文件(也可以直接修改vscode的配置)
settings.json
{
"eslint.validate": ["javascript", "javascriptreact", "typescript", "vue"],
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"editor.formatOnSave": false,
}
然后就可以敲代码的过程中保存直接进行eslint修复了
按上面的配置会发现对.js文件和.vue文件中的js代码和css代码没有任何约束力,这明显不是我们需要的效果,这时就需要prettier登场了
一、安装依赖项 prettier
、eslint-config-prettier
、eslint-plugin-prettier
pnpm i prettier eslint-config-prettier eslint-plugin-prettier -D
二、在项目根路径创建文件 prettier.config.js
prettier.config.js
module.exports = {
endOfLine: 'lf',
printWidth: 120,
singleQuote: true,
semi: false,
}
三、修改 .eslintrc.js
.eslintrc.js
module.exports = {
root: true,
extends: ['plugin:vue/vue3-recommended', 'plugin:prettier/recommended'],
rules: {
'prettier/prettier': 'warn',
'vue/valid-template-root': 'off',
'vue/no-multiple-template-root': 'off',
'vue/multi-word-component-names': [
'error',
{
ignores: ['index', '401', '404'],
},
],
},
}
配置完就会发现在.js文件和.vue文件中不管代码有多乱,Ctrl + S
都能让你的代码立即变得干净整洁,简直不要太爽
如发现配置未生效可重新启动vscode试试
在项目中我们最好是使用统一行尾符(建议不管还是mac还是windows都使用lf),但是按上面的配置,我们发现保存的时候无法将crlf行尾符转换成lf行尾符,当然我们可以直接点击vscode的右下角切换行尾符,但终究是有点麻烦,这时使用.editorconfig就很有必要了
在项目根路径新建文件 .editorconfig
.editorconfig
root = true
[*]
charset = utf-8
end_of_line = lf
这时候保存的时候就可以直接转换成lf行尾符了,当然.editorconfig的作用不仅仅于此,配置得当甚至可以替换eslint和prettier,而且其配置还是跨平台和跨编辑器的
那可不可以在新建文件的时候就确定好使用lf呢,当然也是可以的
.vscode/settings.json
{
...
"files.eol": "\n",
}
eslint+prettier配置篇就介绍完了,我想说的是这套配置并不是一套绝对标准的配置,但是是我目前用得最舒服的配置,也是我目前个人项目一直在用的配置,有一定的约束力又不会用起来难受。
更多eslint rules配置请参考 List of available rules - ESLint中文
阅读量:2015
点赞量:0
收藏量:0