vue3前端代码格式化实践

2,632 阅读7分钟

vscode配置

安装prettier和eslint两个插件

修改默认格式化工具

建议默认使用prettier来做格式化:左下角进入设置->搜索 editor.defaultFormatter,建议修改工作区就行

image.png

prettier

项目安装依赖

npm i prettier -D

编写配置文件

在项目根目录下新建 prettier.config.js 文件以及忽略文件 .prettierignore

prettier.config.js示例:可以参考官网配置

module.exports = {
  printWidth: 120, // 超过最大值换行
  tabWidth: 2, // 缩进字节数
  useTabs: false, // 缩进不使用tab,使用空格
  semi: true, // 句尾添加分号
  singleQuote: true, // 使用单引号代替双引号
  proseWrap: 'preserve', // 默认值。因为使用了一些折行敏感型的渲染器(如GitHub comment)而按照markdown文本样式进行折行 never always
  arrowParens: 'avoid', //  (x) => {} 箭头函数参数只有一个时是否要有小括号。avoid:能省略括号的时候就省略 always:总是省略
  bracketSpacing: true, // 在对象,数组括号与文字之间加空格 "{ foo: bar }"
  // disableLanguages: ['vue'], // 不格式化vue文件,vue文件的格式化单独设置
  endOfLine: 'auto', // 结尾是 \n \r \n\r auto
  eslintIntegration: true, //不让prettier使用eslint的代码格式进行校验
  htmlWhitespaceSensitivity: 'strict', // strict 所有空格都将认定为是有意义的
  ignorePath: '.prettierignore', // 不使用prettier格式化的文件填写在项目的.prettierignore文件中
  jsxBracketSameLine: false, // 在jsx中把'> ' 是否单独放一行
  jsxSingleQuote: false, // 在jsx中使用单引号代替双引号
  // parser: 'babylon', // 格式化的解析器,默认是babylon
  requireConfig: true, // Require a 'prettierconfig' to format prettier
  stylelintIntegration: true, //不让prettier使用stylelint的代码格式进行校验
  trailingComma: 'es5', // 在对象或数组最后一个元素后面是否加逗号(在ES5中加尾逗号)
  tslintIntegration: true, // 不让prettier使用tslint的代码格式进行校验
  vueIndentScriptAndStyle: true, // 是否在Vue文件中对代码和标签进行缩进,script和style部分
};

.prettierignore示例:

/dist/*
.local
.output.js
/node_modules/**

**/*.svg
**/*.sh

/public/*

eslint

eslint虽然可以格式化和校验代码质量,但配合使用时一般是用来做代码的质量检验

安装依赖

eslint:代码质量校验

eslint-plugin-vue:对vue3有更好的支持

eslint-config-prettier:本质上这个工具其实就是禁用掉了一些不必要的以及和Prettier相冲突的ESLint规则

eslint-plugin-prettier:将 prettier 作为 ESLint 的规则来使用,相当于代码不符合 Prettier 的标准时,会报一个 ESLint 错误,同时也可以通过 eslint --fix 来进行格式化

@typescript-eslint/eslint-plugin :typescript语法检测支持

@typescript-eslint/parser :TypeScript代码语法解析

npm install --save-dev eslint eslint-plugin-vue eslint-config-prettier eslint-plugin-prettier

编写配置文件

根目录下新增eslint配置文件 .eslintrc.js 忽略文件 .eslintignore

.eslintrc.js示例:

module.exports = {
  root: true,
  env: {
    browser: true,
    node: true,
    es6: true,
  },
  parser: 'vue-eslint-parser',
  parserOptions: {
    parser: '@typescript-eslint/parser',
    ecmaVersion: 2020,
    sourceType: 'module',
    jsxPragma: 'React',
    ecmaFeatures: {
      jsx: true,
    },
  },
  extends: [
    'plugin:vue/vue3-recommended',
    'plugin:@typescript-eslint/recommended',
    'plugin:prettier/recommended',
  ],
  rules: {
    'vue/script-setup-uses-vars': 'error',
    '@typescript-eslint/ban-ts-ignore': 'off',
    '@typescript-eslint/explicit-function-return-type': 'off',
    '@typescript-eslint/no-explicit-any': 'off',
    '@typescript-eslint/no-var-requires': 'off',
    '@typescript-eslint/no-empty-function': 'off',
    'vue/custom-event-name-casing': 'off',
    'no-use-before-define': 'off',
    '@typescript-eslint/no-use-before-define': 'off',
    '@typescript-eslint/ban-ts-comment': 'off',
    '@typescript-eslint/ban-types': 'off',
    '@typescript-eslint/no-non-null-assertion': 'off',
    '@typescript-eslint/explicit-module-boundary-types': 'off',
    '@typescript-eslint/no-unused-vars': [
      'error',
      {
        argsIgnorePattern: '^_',
        varsIgnorePattern: '^_',
      },
    ],
    'no-unused-vars': [
      'error',
      {
        argsIgnorePattern: '^_',
        varsIgnorePattern: '^_',
      },
    ],
    'space-before-function-paren': 'off',

    'vue/attributes-order': 'off',
    'vue/one-component-per-file': 'off',
    'vue/html-closing-bracket-newline': 'off',
    'vue/max-attributes-per-line': 'off',
    'vue/multiline-html-element-content-newline': 'off',
    'vue/singleline-html-element-content-newline': 'off',
    'vue/attribute-hyphenation': 'off',
    'vue/require-default-prop': 'off',
    'vue/require-explicit-emits': 'off',
    'vue/html-self-closing': [
      'error',
      {
        html: {
          void: 'always',
          normal: 'never',
          component: 'always',
        },
        svg: 'always',
        math: 'always',
      },
    ],
    'vue/multi-word-component-names': 'off',
  },
};

.eslintignore示例:

*.sh
node_modules
*.md
*.woff
*.ttf
.vscode
.idea
dist
/public
/docs
.husky
.local
/bin
Dockerfile

. editorconfig跨端统一格式化

. editorconfig 自定义文件是用来定义编辑器的编码格式规范,编辑器的行为会与  . editorconfig 文件中定义的一致,并且其优先级比编辑器自身的设置要高。 EditorConfig 插件会读取  . editorconfig 文件中定义的内容,应用于编辑器。

所以 EditorConfig 是用来帮助我们在不同的编辑器中保持编码风格的统一的。

但是他的功能比较简单,只能做一些简单的格式化规范,不过好在他的优先级更高,至少能够让团队有个基本的规范,更多的规范就需要用到prettier了

因为他是没有prettier时的替代品,所以他的配置要跟prettier保持统一

vscode插件

安装 EditorConfig for VS Code 部分编辑器不需要安装插件

.editorconfig配置

根目录下新建 .editorconfig 文件

只需要安装好插件,并添加配置文件,格式化规则就会自动生效

示例配置:

root = true # 表示该文件是项目的根配置文件,编辑器在查找配置时会从当前文件夹开始逐级向上查找,直到找到该文件为止

# 表示所有文件适用
[*]
charset=utf-8 # 设置文件字符集为 utf-8
end_of_line=lf # 控制换行符类型 lf(Unix 风格)、cr(Mac 风格)或 crlf(Windows 风格)
insert_final_newline=true # 始终在文件末尾插入一个新行
indent_style=space # 缩进风格(tab | space)
indent_size=2 # 缩进大小
max_line_length = 100 # 设置每行的最大字符数。可选值为整数

[*.{yml,yaml,json}]
indent_style = space
indent_size = 2

[*.md] # 表示仅 md 文件适用以下规则
trim_trailing_whitespace = false # 去除行首的任意空白字符

[Makefile]
indent_style = tab

注意,有可能这个文件会被隐藏,取消隐藏的方式:在设置中搜索 files.exclude,如下图,找到文件把他删掉就行

image.png

优先级

至此项目中的一整套格式化工具就处理完成了,需要注意的是其中有优先级的限制,常见的prettier和eslint的冲突已经可以通过上述的插件等方式解决,剩下的就是editorconfig,他的优先级是低于prettier的,大家可以尝试注释掉prettier中的某项配置,editorconfig对应的配置就会生效

小结

所以目前为止,这些工具的具体分工如下:

  • eslint: 代码质量校验
  • prettier: 代码格式化
  • editorconfig: 跨端代码格式化 -- 优先级低于 prettier

提交git自动格式化代码

这种方式格式化不需要依赖于插件,所以能够做到不同的编辑器跨端的代码格式化,不用担心多人开发时,有人使用了不同的开发工具。

工作原理:首先我们参照上文,在项目安装了prettier 和 eslint相关的开发依赖,然后提交代码时,会触发对应的钩子,使用本地依赖的prettier去格式化代码,格式化完成后再提交代码。而且我们可以再加一些规范进去,比如commit信息必须加上前缀:add feat test fix等等,不标准的提交会报错阻止提交。

依赖

prettier:上面已经介绍安装过了

husky:提供gitHook相关功能

lint-staged:让命令只对发生更改的文件生效

安装步骤参照官网 www.prettier.cn/docs/instal…

image.png

配置commit参照官网 www.prettier.cn/docs/precom… 执行option1即可

image.png

安装好之后,会在项目下生成文件.husky,这时已经配置好了, 他会在你每次commit之前执行npx lint-staged,这个命令会执行prettier --write,并且只对本次修改的文件生效

prettier配置文件参考上文

win电脑.prettierrc.json写入失败

使用vscode中powershell执行echo {}> .prettierrc.json

配置gitHook之后 commit不会自动格式化vue文件

参考package.json中的lint-staged配置:

"lint-staged": {
    "*.{js,jsx,ts,tsx}": [
      "eslint --fix",
      "prettier --write"
    ],
    "{!(package)*.json,*.code-snippets,.!(browserslist)*rc}": [
      "prettier --write--parser json"
    ],
    "package.json": [
      "prettier --write"
    ],
    "*.vue": [
      "eslint --fix",
      "prettier --write",
      "stylelint --fix"
    ],
    "*.{scss,less,styl,html}": [
      "stylelint --fix",
      "prettier --write"
    ],
    "*.md": [
      "prettier --write"
    ]
  }

mac电脑上可能会报错:因为没有将钩子 '.husky/pre-commit' 设置为可执行 钩子被忽略

解决方法:执行以下命令,将文件改为可执行即可

chmod +x .husky/pre-commit

格式化未生效 输出cjs错误

检查package.json中的type

image.png

这个代表使用es module规范,如果你的配置文件是module.exports 就肯定会报错,一种是改成cjs后缀,一种是改为export default