vue+eslint+prettier格式化

2022年6月10日12:55:20

背景

新建一个 Vue 项目pro_demo并选择自定义模式

vue create pro_demo

vue+eslint+prettier格式化
vue+eslint+prettier格式化
vue+eslint+prettier格式化
现在我们来测试一下代码规范,在Home.vue 文件中
vue+eslint+prettier格式化
有三种方式可以自动格式化这些不符合规范的代码

手动格式化

vue+eslint+prettier格式化

命令行指令

// package.json文件中"scripts":{"serve":"vue-cli-service serve","build":"vue-cli-service build","lint":"vue-cli-service lint","fix":"vue-cli-service lint --fix"// 新增这一条指令},

然后执行命令

npm run fix

或者

npm run lint--fix

vscode设置

如果想要保存文件的时候就自动执行格式化操作,需要再vscode的配置首选项里增加下面内容即可

// settion.json"editor.codeActionsOnSave":{"source.fixAll.eslint":true}

配合使用vscode插件

  • Eslint
  • Prettier

自定义校验规则

我们发现此时的校验规则是分号结尾,使用双引号,但是我的个人习惯是不用分号结尾,且使用的是单引号,那如何自定义我们的校验规则呢?

// .eslintrc.jsrules:{"no-console": process.env.NODE_ENV==="production"?"warn":"off","no-debugger": process.env.NODE_ENV==="production"?"warn":"off",// 自定义校验规则"prettier/prettier":[// 自定义不满足规则的提示,error还是warn'error',{singleQuote:true,// 使用单引号semi:false,// 不使用分号结尾trailingComma:'none',// 对象后面不默认添加逗号endOfLine:'auto',// 如果你有报错【Delete `CR` eslint】arrowParens:'avoid',// 箭头函数只有一个参数时不需要括号printWidth:100// 指定长度换行}]}

eslint扩展配置文件

一个 ESlint 配置文件,一旦扩展(extends)了就能继承另一个配置文件的所有属性,然后通过 merge 合并/覆盖所有原来的配置

eslint:recommended

eslint:recommended 这个扩展包帮我们启用了一系列核心规则,这些规则都是eslint官网推荐的规则的勾选项,如果你想在项目中查看可以去查找对应的包
vue+eslint+prettier格式化

plugin:vue/vue3-essential

node_modules/eslint-plugin-vue 中通过package.json 指定的入口文件"main": "lib/index.js"' 中找到
vue+eslint+prettier格式化
如果你使用的是vue2.x,配置是plugin:vue/essential 那就是对应的essential 文件内容

附录

其他关于ESlint 的配置可以参考eslint配置项列表eslint中文官网去查看配置步骤

  • 作者:土豆Coder
  • 原文链接:https://blog.csdn.net/weixin_43443341/article/details/124127731
    更新时间:2022年6月10日12:55:20 ,共 1393 字。