• Vue2/3 项目中的 ESLint + Prettier 代码检测格式化风格指南


    Vue2/3 项目中的 ESLint + Prettier 代码检测格式化风格指南

    因为平时都是使用 VSCode ESLint + Prettier 检测格式化不规范代码,但是随着接手的项目越来越多,需要统一每个项目的代码规范,于是在此分享vue项目的几种代码格式化风格(default,standard,airbnb,prettier)的基本区别以及修改为prettier风格。

    对比肉眼可见的格式化风格差异,并且以字符串单/双引号,每行结尾有无分号,object对象最后一项有无尾逗号作为判断依据

    VSCode的插件以及配置

    • ESLint , Prettier 插件安装

    • 配置VSCode settings.json

      ...
      // 相应文件的格式化工具选中
    	"[vue]": {
    	  "editor.defaultFormatter": "esbenp.prettier-vscode"
    	},
    	"[jsonc]": {
    		"editor.formatOnSave": true,
    		"editor.defaultFormatter": "esbenp.prettier-vscode"
    	},
    	"[json]": {
    		"editor.formatOnSave": true,
    		"editor.defaultFormatter": "esbenp.prettier-vscode"
    	},
    	"[css]": {
    		"editor.formatOnSave": true,
    		"editor.defaultFormatter": "esbenp.prettier-vscode"
    	},
    	"[scss]": {
    		"editor.formatOnSave": true,
    		"editor.defaultFormatter": "esbenp.prettier-vscode"
    	},
    	"[typescript]": {
    		"editor.defaultFormatter": "esbenp.prettier-vscode"
    	},
    	"[javascript]": {
    		"editor.defaultFormatter": "esbenp.prettier-vscode"
    	},
    	"[javascriptreact]": {
    		"editor.defaultFormatter": "esbenp.prettier-vscode"
    	},
    	"[html]": {
    		"editor.defaultFormatter": "esbenp.prettier-vscode"
    	},
      // 启用ESLint作为已验证文件的格式化程序,可方便快捷键
      "eslint.format.enable": true, 
      // 每次保存的时候将代码按eslint格式进行修复
      "editor.codeActionsOnSave": {
    		"source.fixAll.eslint": true
    	},
      // 关闭编辑器默认保存格式化,不然多数情况会和上面的配置执行两次
      "editor.formatOnSave": false
      ...
    

    1. 【 Default 】 vue/cli 创建默认配置项目

    1. 运行以下命令来创建一个新项目:
      vue create hello-world
    2. 选择 Default ([Vue 2] babel, eslint) 回车创建
      avatar

    等着创建成功后,会发现 eslint 的相关配置,在package.json文件中:

      "eslintConfig": {
        "root": true,
        "env": {
          "node": true
        },
        "extends": [
          "plugin:vue/essential",
          "eslint:recommended"
        ],
        "parserOptions": {
          "parser": "babel-eslint"
        },
        "rules": {}
      },
    

    这里我们删除它,并在项目下新建.eslintrc.js文件将其迁移进去:

    module.exports = {
        "root": true,
        "env": {
          "node": true
        },
        "extends": [
          "plugin:vue/essential",
          "eslint:recommended"
        ],
        "parserOptions": {
          "parser": "babel-eslint"
        },
        "rules": {}
      }
    

    plugin:vue/essential:启用 vue 的基础规则
    eslint:recommended:启用 eslint 的推荐规则

    babel-eslint:可以对所有有效的babel代码进行lint处理。

    此时我们可以根据当前项目中main.js文件发现,最基本的风格为:字符串单引号,结尾无分号;当我们结尾加分号,保存测试会没有任何效果,不要急,接下来添加 prettier 。

    vue/cli 添加 prettier

    运行以下命令:
    vue add @vue/eslint

    提示 Still proceed 选择 y
    等待安装完
    会出现四个格式化风格选择项,按向下键,选择 Prettier 回车确认
    再选择 Lint on save 回车确认

    等 @vue/cli-plugin-eslint 安装完成后会发现 .eslintrc 配置中 extends 多出了@vue/prettier

    回过头来,再去项目的main.js或者App.vue文件保存测试发现格式化生效。

    最后,去除一些常规的eslint 报错警告信息,在 rules 中添加自定义规则:

    其中 "prettier/prettier" 可以添加 prettier 相关配置

    .eslintrc.js 完整配置

    module.exports = {
      "root": true,
      "env": {
        "node": true
      },
      "extends": [
        "plugin:vue/essential",
        "eslint:recommended",
        "@vue/prettier"
      ],
      "parserOptions": {
        "parser": "babel-eslint"
      },
      "rules": {
        'prettier/prettier': [
    			'error',
    			{
    				requireConfig: false,
    				endOfLine: 'auto',
    				quoteProps: 'as-needed',
    				proseWrap: 'preserve',
    				arrowParens: 'always',
    				htmlWhitespaceSensitivity: 'strict',
    				ignorePath: '.prettierignore',
    				jsxBracketSameLine: false,
    				jsxSingleQuote: false,
    				vueIndentScriptAndStyle: true,
    				semi: false,
    				trailingComma: 'none',
    				singleQuote: true,
    				printWidth: 150,
    				tabWidth: 2,
    				bracketSpacing: true,
    				useTabs: true
    			}
    		],
    		'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
    		'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
    		'vue/v-on-event-hyphenation': 'off',
    		'vue/multi-word-component-names': ['off'],
    		'vue/prop-name-casing': 'off',
    		'vue/require-default-prop': 'off',
    		'vue/no-v-html': 'off',
    		'no-new': 'off',
    		'prefer-regex-literals': 'off',
    		'prefer-promise-reject-errors': 'off',
    		'no-unused-vars': [
    			'off',
    			{
    				caughtErrors: 'none'
    			}
    		],
    		'vue/no-unused-vars': [
    			'off',
    			{
    				caughtErrors: 'none'
    			}
    		],
    		'no-tabs': 'off',
    		'no-trailing-spaces': 'off',
    		'no-mixed-spaces-and-tabs': 'off',
    		'no-empty-function': 'off',
    		'space-before-function-paren': ['off', 'always'],
    		'no-unreachable-loop': 'off',
    		'no-multiple-empty-lines': 'off',
    		'no-loss-of-precision': 'off',
    		'no-useless-escape': 0,
    		semi: ['warn', 'never'],
    		eqeqeq: 0,
    		indent: ['off', 2],
    		quotes: ['error', 'single', { allowTemplateLiterals: true }]
      }
    }
    

    2. 【 Manually 】 vue/cli 自定义创建 ESLint + Prettier

    1. 运行以下命令来创建一个新项目:
      vue create hello-world
    2. Please pick a preset: 选择 Manually select features
    3. Check the features needed for your project: Choose Vue version, Babel, Linter...
    4. Choose a version of Vue.js that you want to start the project with 2.x
    5. Pick a linter / formatter config: Prettier
    6. Pick additional lint features: Lint on save
    7. Where do you prefer placing config for Babel, ESLint, etc.?: In dedicated config files
    8. Save this as a preset for future projects? Yes
    9. Save preset as: 回车确认

    可见差异:字符串双引号,每行结尾有分号,object对象最后一项有尾逗号;

    生成的.eslintrc.js 中 extends: ["plugin:vue/essential", "eslint:recommended", "@vue/prettier"]

    跟上面 [1. 【 Default 】 vue/cli 创建默认配置项目] 创建的.eslintrc.js 配置对比发现,只是少了 rules 配置,将上面的 rules 配置copy过来。同样测试保存格式化效果一样。

    3. 【 Manually 】 vue/cli 自定义创建 ESLint + Standard

    1. 运行以下命令来创建一个新项目:

    vue create hello-world

    1. Please pick a preset: Manually select features
    2. Check the features needed for your project: Choose Vue version, Babel, Linter
    3. Choose a version of Vue.js that you want to start the project with 2.x
    4. Pick a linter / formatter config: Standard
    5. Pick additional lint features: Lint on save
    6. Where do you prefer placing config for Babel, ESLint, etc.? In dedicated config files
    7. Save this as a preset for future projects? Yes
    8. Save preset as:回车确认

    可见差异:字符串单引号,每行结尾无分号,对象最后一项没有尾逗号;

    生成的.eslintrc.js 中 extends: ["plugin:vue/essential", "@vue/standard"]

    关于.eslintrc.js配置,去掉 rules 中的 'prettier/prettier' ,rules其他配置同上,同样测试保存格式化效果一样。

    4. 【 Manually 】 vue/cli 自定义创建 ESLint + Airbnb

    1. 运行以下命令来创建一个新项目:

    vue create hello-world

    1. Please pick a preset: Manually select features
    2. Check the features needed for your project: Choose Vue version, Babel, Linter
    3. Choose a version of Vue.js that you want to start the project with 2.x
    4. Pick a linter / formatter config: Airbnb
    5. Pick additional lint features: Lint on save
    6. Where do you prefer placing config for Babel, ESLint, etc.? In dedicated config files
    7. Save this as a preset for future projects? Yes
    8. Save preset as:回车确认

    可见差异:字符串单引号,每行结尾有分号,对象最后一项有尾逗号;

    生成的.eslintrc.js 中 extends: ["plugin:vue/essential", "@vue/airbnb"]

    关于.eslintrc.js配置,rules其他配置同上,同样测试保存格式化效果基本一致一样。

    5. vite 自定义创建默认Vue项目

    1. 运行以下命令来创建一个新项目:

    npm init vite@latest my-vue-app --template vue

    2. 安装 vue3 ESLint + Prettier 相关依赖

    npm install eslint-config-tkb -D

    然后在package.json 中新添加配置即可:

    "eslintConfig": {
    	"extends": ["eslint-config-tkb"]
    }
    

    进入vue和js 文件保存,测试格式化效果基本一致一样。

    eslint-config-tkb 是个人自定义的 eslESLint + Prettier 的配置,也支持vite创建的 vue-ts创建的模板项目。

  • 相关阅读:
    1.5状态压缩DP
    MAVEN在IDEA中的使用
    husky + lint-staged + commitizen 配置提交代码规范
    深度学习神经网络实战:多层感知机,手写数字识别
    初识C++ (一)
    短视频剪辑:如何批量调整播放倍速,轻松掌控节奏?
    汽车称重软件系统配置(一)
    10 种常见的BUG分类
    Python 全栈测试开发 Chapter8:接口测试
    JS 数组扁平化
  • 原文地址:https://www.cnblogs.com/TBNICE/p/15964330.html