前端工程化之 eslint & prettier

371 阅读2分钟

前言

在企业应用中,多人参与开发,为了更好的把控代码质量与代码规范,通用方法都是添加 eslint 进行代码校验。prettier 进行代码格式化。

这里以 vite + vue3 + ts 创建的项目进行演示,其他框架操作步骤也一样。

eslint

安装eslint

npm install eslint --save-dev

初始化

npx eslint --init

初始化选项

选择你的 eslint 配置,根据你的实际情况选择,Which framework does your project use? 就是选择你需要的框架语言。

选择 vue 之后会提示让你安装几个 vue 下的 eslint 配置包,安装即可。

image.png

安装完成

此时需要在 vscode 中搜索eslint插件进行安装,这样就不用每次都使用命令去校验代码,自动化检测。

image.png

错误提示

使用时,可能出现的两个错误,需要在 .eslintrc.js 中进行配置。

"env": {
    "browser": true,
    "es2021": true,
    "node": true, // 增加
},
"parser": "vue-eslint-parser", // 增加

image.png

image.png

prettier

安装插件

npm install prettier --save-dev

配置项

根目录下新建 .prettierrc.js 更多配置参考官网

由于个人不喜欢保存时自动格式化,所以没有配置自动方案,如有需要请查看此文章

module.exports = {
    // 一行的字符数,如果超过会进行换行,默认为80
    printWidth: 80, 
    // 一个tab代表几个空格数,默认为80
    tabWidth: 2, 
    // 是否使用tab进行缩进,默认为false,表示用空格进行缩减
    useTabs: false, 
    // 字符串是否使用单引号,默认为false,使用双引号
    singleQuote: true, 
    // 行位是否使用分号,默认为true
    semi: false, 
    // 是否使用尾逗号,有三个可选值"<none|es5|all>"
    trailingComma: "none", 
    // 对象大括号直接是否有空格,默认为true,效果:{ foo: bar }
    bracketSpacing: true
}

参考资料

eslint官网

prettier官网

文章1

文章2