配合一系列的linter规范你的项目

前言

一个成熟的企业或者开源项目,都会有一定的团队规范,不然每个成员都有不一样的代码风格,就会变得难以维护。那么,我们在项目中如何保证团队规范呢?一般我们都是利用公司团队内的技术要求说明文档(文件命名规范等)配合相关的linter(代码规范检查)进行约束。
那么,如何将想要的linter配置到我们编写的项目中呢?本文带你一一了解。(注:本文大都是来自对应linter官网和vben-admin的配置,进行学习和操作。)

Husky

husky

?‍♂️husky可以约束git commit过程中 提供一系列的hooks,让用户在git commit 的过程中,做一些用户想要执行的命令。比如规范化msg的书写规范,这样可以让根据commit的信息,让团队成员快速理解每一
次的commit解决的问题,方便合作和 code review

目前husky支持git的所有钩子,具体git 支持的钩子,参考git官网。我们常用的就是 pre-commitcommit-msg

旧版本的husky

⚠️ 版本在v4以下

安装

yarn add -D husky@4
复制代码

添加 git hooks

// package.json
"husky": {
    "hooks": {
      "pre-commit": "ls-lint && lint-staged",
      "commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
    }
  }
复制代码
  • pre-commit: 在commit之前,husky会执行的脚本命令,一般做一些语法校验和有eslint,stylelint等操作
  • commit-msg: 这个可以对你commit注释的信息进行一个校验,常用的commit注释标准就是angular的提交信息标准

新版本的husky

⚠️ 注意:安装 husky之前,请先检查您使用的yarn版本,如果是yarn2,请参考

安装

yarn add -D husky
复制代码

启用hooks

npx husky install
复制代码

创建脚本

// package.json
"scripts": {
  "install:husky": "husky install",
}
复制代码

增加hooks

⚠️: 注意,增加hooks前,必须先安装一下husky

npx husky add .husky/pre-commit "npm run your script"
复制代码

FAQ

CI(持续集成)环境hooks被绕过

客户端校验是不可信的,通过一条命令即可绕过 git hooks

git commit -n
复制代码

git hooks 可以绕过,但 CI(持续集成) 是绝对绕不过的,因为它在服务端校验。

但是默认情况下,Husky 不会安装在 CI 服务器上。解决方案

利用is-ci,判断当前环境是不是CI环境,让CI环境也安装上husky,

  1. 安装
yarn add -D is-ci
复制代码
  1. 添加脚本命令
// package.json
"install:husky": "is-ci || husky install",
复制代码
  1. pre-commit钩子上添加
[ -n "$CI" ] && exit 0
复制代码

commitlint.config.js

commit的填写信息,也想添加上lint规则

commitlint就是专门解决这种场景的工具,使用步骤如下

  1. 安装commitlint

      yarn add -D @commitlint/config-conventional @commitlint/cli
    复制代码
  2. 添加hooks

    npx husky add .husky/commit-msg 'npx --no-install commitlint --edit "$1"'
    复制代码
  3. 添加配置文件commitlint.config.js到根目录

    module.exports = {
      ignores: [(commit) => commit.includes('init')],
      extends: ['@commitlint/config-conventional'],
      parserPreset: {
        parserOpts: {
          headerPattern: /^(\w*|[\u4e00-\u9fa5]*)(?:[\(\(](.*)[\)\)])?[\:\:] (.*)/,
          headerCorrespondence: ['type', 'scope', 'subject'],
          referenceActions: [
            'close',
            'closes',
            'closed',
            'fix',
            'fixes',
            'fixed',
            'resolve',
            'resolves',
            'resolved',
          ],
          issuePrefixes: ['#'],
          noteKeywords: ['BREAKING CHANGE'],
          fieldPattern: /^-(.*?)-$/,
          revertPattern: /^Revert\s"([\s\S]*)"\s*This reverts commit (\w*)\./,
          revertCorrespondence: ['header', 'hash'],
          warn() {},
          mergePattern: null,
          mergeCorrespondence: null,
        },
      },
      rules: {
        'body-leading-blank': [2, 'always'],
        'footer-leading-blank': [1, 'always'],
        'header-max-length': [2, 'always', 108],
        'subject-empty': [2, 'never'],
        'type-empty': [2, 'never'],
        'type-enum': [
          2,
          'always',
          [
            'feat',
            'fix',
            'perf',
            'style',
            'docs',
            'test',
            'refactor',
            'build',
            'ci',
            'chore',
            'revert',
            'wip',
            'workflow',
            'types',
            'release',
          ],
        ],
      },
    };
    复制代码

common.sh

window平台git hooks有时候可能会失败
在 Windows 上通过 Git Bash ( stdin is not a tty)使用 Yarn 时,Git 钩子可能会失败。如果您有 Windows 用户,强烈建议添加以下解决方法。

  1. 创建.husky/common.sh
#!/bin/sh
command_exists () {
  command -v "$1" >/dev/null 2>&1
}
if command_exists winpty && test -t 1; then
  exec < /dev/tty
fi
复制代码
  1. pre-commit的钩子上添加上
#!/bin/sh
+ # add common.sh
+ . "$(dirname "$0")/common.sh"
复制代码

lint-staged

每次lint的过程都是全部校验,想局部校验
首先明确一下,Lint-staged仅仅是文件过滤器,不会帮你格式化任何东西,所以没有代码规则配置文件,需要自己配置一下,如:.eslintrc.stylelintrc等,然后在package.json中引入。

换句话说,lint-staged可以让你跟husky一样,在git 的对应hooks可以帮你执行绑定的格式化命令,可以理解成就是负责维护每次提交时只检查本次提交的暂存区的文件对应lint的配置规则的文件作用而已。

# pre-commit
#!bin/sh
. "$(dirname "$0")/_/husky.sh"
. "$(dirname "$0")/common.sh"
[ -n "$CI" ] && exit 0
复制代码
 "lint-staged": {
    "*.js": ["eslint --fix", "git add"]
  }
复制代码

当文件变化,我们git commit它们,pre-commit钩子会启动,执行lint-staged命令,我们对于lint-staged如上文配置,对本次被commited中的所有.js文件,执行eslint --fix命令和git add,命令,前者的的目的是格式化,后者是对格式化之后的代码重新提交。

使用步骤

  1. 安装
yarn add -D lint-staged
复制代码
  1. 添加脚本命令
// package.json
"scripts": {
  "lint:lint-staged": "lint-staged -c ./.husky/lint-staged.config.js"
}
复制代码
  1. 在pre-commit的钩子上添加lint-staged命令
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
. "$(dirname "$0")/common.sh"
[ -n "$CI" ] && exit 0
npm run lint:lint-staged
复制代码
  1. 添加你想要的配置文件。这里就以vben-admin的项目配置为参考
// .husky/lint-staged.config.js
module.exports = {
  '*.{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'],
};
复制代码

Prettier

转载自

?‍♂️ 对js或者ts等代码进行格式化,可以保证团队的代码风格保持一致。

那么,如何使用到我们的项目中呢。更多细节,请戳这里

安装

yarn add -D prettier
复制代码

如果需要与git hooks配合,那么可以走下面的步骤.当然,本教程已经集成husky,可以了解前面的husky安装。

prettier.config.js

module.exports = {
  printWidth: 100,
  tabWidth: 2,
  useTabs: false,
  semi: true,
  vueIndentScriptAndStyle: true,
  singleQuote: true,
  quoteProps: 'as-needed',
  bracketSpacing: true,
  trailingComma: 'es5',
  jsxBracketSameLine: false,
  jsxSingleQuote: false,
  arrowParens: 'always',
  insertPragma: false,
  requirePragma: false,
  proseWrap: 'never',
  htmlWhitespaceSensitivity: 'strict',
  endOfLine: 'lf',
  rangeStart: 0,
};
复制代码

添加脚本命令

// package.json
"scripts": {
  "lint:prettier": "prettier --write --loglevel warn \"src/**/*.{js,json,tsx,css,less,scss,vue,html,md}\"",
}
复制代码
// .husky/lint-staged.config.js
module.exports = {
  '*.{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'],
  '*.{scss,less,styl,html}': ['prettier --write'],
  '*.md': ['prettier --write'],
};
复制代码

.prettierignore

# 以下文件夹不会被格式化
/dist/*
.local
.output.js
/node_modules/**
**/*.svg
**/*.sh
/public/*
复制代码

pretty-quick

pretty-quick也是一款类似于lint-staged的代码检查平台,不过于lint-staged的区别在于,pretty-quick是在 git commit之前,先到暂存区配合prettier进行代码格式化,然后重新add到暂存区。而lint-staged是对暂存区的代码进行lint,执行文件对应的格式化配置

使用步骤:

  • 安装

    yarn add -D prettier pretty-quick
    复制代码
  • 添加脚本命令

    "scripts": {
      "lint:pretty": "pretty-quick --staged",
    }
    复制代码

    --staged :这个配置是告诉linter只在git阶段生效

  • 添加 hooks

    npx husky add .husky/pre-commit "npm run lint:pretty"
    复制代码

Eslint

转载自

?‍♀️ Eslint是用于约束js或者ts代码中的一些语法,让编写者能够及时发现编写上的语法错误。具体的作用,相信笔者不用多提,大家也都听过他的鼎鼎大名。在此,就不在花篇幅进行介绍了。

下面,让我们学习一下,怎样才能集成到我们的项目。

了解之前可以先戳一下官网测试一下喔

安装依赖

yarn add -D eslint eslint-define-config
复制代码

.eslintrc.js

在项目根目录下建立.eslintrc.js或者eslint.config.js,编写你要lint的相关语法规则,详情可以查看官网的配置

//.eslintrc.js
const { defineConfig } = require('eslint-define-config');
module.exports = defineConfig({
    root: true,
  env: {
    browser: true,
    node: true,
    es6: true,
  },
  rules: {
       'no-use-before-define': 'off', 
    'no-unused-vars': [
      'error',
      {
        argsIgnorePattern: '^_',
        varsIgnorePattern: '^_',
      },
    ],
    'space-before-function-paren': 'off',
  }
})
复制代码

.eslintignore

添加你不想被eslint校验的文件

*.sh
node_modules
*.md
*.woff
*.ttf
.vscode
.idea
dist
/public
/docs
.husky
.local
/bin
Dockerfile
复制代码
  1. 添加脚本命令
// package.json
"scripts": {
   "lint:eslint": "eslint \"{src,mock}/**/*.{vue,js,ts,tsx}\" --fix",
}
复制代码
// .husky/lint-staged.config.js
module.exports = {
  '*.{js,jsx,ts,tsx}': ['eslint --fix'],
};
复制代码

⚠️ 注意:

  • 添加--fix可以开启eslint的自动修复功能。
  • 如果您使用的编辑起是vscode,请安装eslint的插件进行使用喔
  • 有时候,有时候编辑器的问题,配置不会立马生效,需要重新开启项目,让编辑器重新加载配置。

Prettier配合

  1. 安装

    yarn add -D eslint-config-prettier eslint-plugin-prettier
    复制代码
    • eslint-config-prettier:关闭所有与eslint冲突的规则,请注意,该插件只有关闭冲突的规则的作用
    • eslint-plugin-prettier:如果您禁用与代码格式相关的所有其他 ESLint 规则,并且仅启用检测潜在错误的规则,则此插件效果最佳。换句话说,就是你想单独配置某一项时,使用这个插件。值得一提的是,这个插件附带了一个plugin:prettier/recommended配置,可以eslint-config-prettier一次性设置插件。该配置最主要的就是解决回调函数的格式化问题。
  2. 修改.eslintrc

    {
      extends: [
        "prettier",
        "plugin:prettier/recommended"
      ]
    }
    复制代码

Stylelint

图片转载自

?‍♂️ Stylelint是一款强大的现代 linter,可帮助您避免错误并强制执行样式中的约定,帮助统一团队中书写样式代码的规则。被广泛用于一系列大型项目

如何将其集成到项目中呢?详情请戳这里

安装

yarn add -D stylelint stylelint-config-standard stylelint-order
复制代码
  • stylelint stylelint-config-standard: 官方需要下载的stylelint安装包
  • stylelint-order: 可以自定义样式代码编写顺序的styllint插件

stylelint.config.js

module.exports = {
  root: true,
  plugins: ['stylelint-order'],
  extends: ['stylelint-config-standard'],
  rules: {
    'selector-pseudo-class-no-unknown': [
      true,
      {
        ignorePseudoClasses: ['global'],
      },
    ],
    'selector-pseudo-element-no-unknown': [
      true,
      {
        ignorePseudoElements: ['v-deep'],
      },
    ],
    'at-rule-no-unknown': [
      true,
      {
        ignoreAtRules: ['function', 'if', 'each', 'include', 'mixin'],
      },
    ],
    'no-empty-source': null,
    'named-grid-areas-no-invalid': null,
    'unicode-bom': 'never',
    'no-descending-specificity': null,
    'font-family-no-missing-generic-family-keyword': null,
    'declaration-colon-space-after': 'always-single-line',
    'declaration-colon-space-before': 'never',
    'declaration-block-trailing-semicolon': 'always',
    'rule-empty-line-before': [
      'always',
      {
        ignore: ['after-comment', 'first-nested'],
      },
    ],
    'unit-no-unknown': [true, { ignoreUnits: ['rpx'] }],
    'order/order': [
      [
        'dollar-variables',
        'custom-properties',
        'at-rules',
        'declarations',
        {
          type: 'at-rule',
          name: 'supports',
        },
        {
          type: 'at-rule',
          name: 'media',
        },
        'rules',
      ],
      { severity: 'warning' },
    ],
    // Specify the alphabetical order of the attributes in the declaration block
    'order/properties-order': [
      'position',
      'top',
      'right',
      'bottom',
      'left',
      'z-index',
      'display',
      'float',
      'width',
      'height',
      'max-width',
      'max-height',
      'min-width',
      'min-height',
      'padding',
      'padding-top',
      'padding-right',
      'padding-bottom',
      'padding-left',
      'margin',
      'margin-top',
      'margin-right',
      'margin-bottom',
      'margin-left',
      'margin-collapse',
      'margin-top-collapse',
      'margin-right-collapse',
      'margin-bottom-collapse',
      'margin-left-collapse',
      'overflow',
      'overflow-x',
      'overflow-y',
      'clip',
      'clear',
      'font',
      'font-family',
      'font-size',
      'font-smoothing',
      'osx-font-smoothing',
      'font-style',
      'font-weight',
      'hyphens',
      'src',
      'line-height',
      'letter-spacing',
      'word-spacing',
      'color',
      'text-align',
      'text-decoration',
      'text-indent',
      'text-overflow',
      'text-rendering',
      'text-size-adjust',
      'text-shadow',
      'text-transform',
      'word-break',
      'word-wrap',
      'white-space',
      'vertical-align',
      'list-style',
      'list-style-type',
      'list-style-position',
      'list-style-image',
      'pointer-events',
      'cursor',
      'background',
      'background-attachment',
      'background-color',
      'background-image',
      'background-position',
      'background-repeat',
      'background-size',
      'border',
      'border-collapse',
      'border-top',
      'border-right',
      'border-bottom',
      'border-left',
      'border-color',
      'border-image',
      'border-top-color',
      'border-right-color',
      'border-bottom-color',
      'border-left-color',
      'border-spacing',
      'border-style',
      'border-top-style',
      'border-right-style',
      'border-bottom-style',
      'border-left-style',
      'border-width',
      'border-top-width',
      'border-right-width',
      'border-bottom-width',
      'border-left-width',
      'border-radius',
      'border-top-right-radius',
      'border-bottom-right-radius',
      'border-bottom-left-radius',
      'border-top-left-radius',
      'border-radius-topright',
      'border-radius-bottomright',
      'border-radius-bottomleft',
      'border-radius-topleft',
      'content',
      'quotes',
      'outline',
      'outline-offset',
      'opacity',
      'filter',
      'visibility',
      'size',
      'zoom',
      'transform',
      'box-align',
      'box-flex',
      'box-orient',
      'box-pack',
      'box-shadow',
      'box-sizing',
      'table-layout',
      'animation',
      'animation-delay',
      'animation-duration',
      'animation-iteration-count',
      'animation-name',
      'animation-play-state',
      'animation-timing-function',
      'animation-fill-mode',
      'transition',
      'transition-delay',
      'transition-duration',
      'transition-property',
      'transition-timing-function',
      'background-clip',
      'backface-visibility',
      'resize',
      'appearance',
      'user-select',
      'interpolation-mode',
      'direction',
      'marks',
      'page',
      'set-link-source',
      'unicode-bidi',
      'speak',
    ],
  },
  ignoreFiles: ['**/*.js', '**/*.jsx', '**/*.tsx', '**/*.ts'],
};
复制代码

.stylelintignore

/dist/*
/public/*
public/*
复制代码

添加脚本命令

// package.json
"scripts": {
      "lint:stylelint": "stylelint --fix \"**/*.{vue,less,postcss,css,scss}\" --cache --cache-location node_modules/.cache/stylelint/"
}
复制代码

lint-staged

// .husky/lint-staged.config.js
module.exports={
  '*.{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'],
 + '*.{css,scss,less,styl,html}': ['stylelint --fix', 'prettier --write'],
  '*.md': ['prettier --write'],
}
复制代码

Prettier配合

  • 安装

    yarn add -D stylelint-config-prettier
    复制代码

    stylelint-prettier可以配合prettier对样式的代码进行格式化

  • 修改stylelint.config.js

    + extends: ['stylelint-config-standard', 'stylelint-config-prettier'],
    复制代码

Typescript

来自官网

项目中集成Typescript

安装

yarn add -D typescript
复制代码

生成tsconfig.json

# 请确保安装了tsc编译器
yarn global add tsc
# 在项目的根目录初始化ts配置
tsc --init
复制代码

定制化tsconfig.json

?‍♂️ 具体配置可以参考官网的说明

{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig.json to read more about this file */
    /*********************************************************** Basic Options ***********************************************************/
    // 使用的es版本  esnext表示最高
    "target": "esnext",
    // tsc编译后的规范文件
    "module": "commonjs",
    // 制定要加载的内置检测库,不设置默认导入全部
    "lib": ["dom", "esnext"],
    // 是否允许引入js文件
    "allowJs": true,
    // js文件关闭检测
    "checkJs": false,
    // jsx代码编译后的规范
    "jsx": "preserve",
    // 生成编译前代码的映射文件
    "sourceMap": true,
    // 是否采用严格模式
    "strict": true,
    // 是否严格检查函数的参数类型
    "strictFunctionTypes": false,
    // 编译后的每一个文件加上严格模式 'use strict'
    "alwaysStrict": true,
    // 结果是否包括undefined
    "noUncheckedIndexedAccess": false,
    /* **********************************************************Module Resolution Options 模块化的配置***********************************************************/
    // 编译的模块化的方案
    "moduleResolution": "node",
    // 开始查找ts文件的基础目录
    "baseUrl": "./",
    // 路径别名,通过某个标识符指定特定的目录
    "paths": {
      "@/*": ["src/*"],
      "#/*": ["types/*"]
    },
    // 默认情况下不管你是什么目录,,所有可见的“ @types”包都包含在您的编译中。
    //指定目录后可以减少编译,因为缩小了类型文件的搜索范围
    "typeRoots": ["./node_modules/@types/", "./types"],
    // 仅编译以下的类型的包,其他没有指定的包不进行编译
    "types": ["vite/client"],
    // 允许合成默认导出
    "allowSyntheticDefaultImports": true,
    // 允许ts文件中,同时引入 es和commonJS规范的文件
    "esModuleInterop": true,
    // 允许声明全局变量来访问,比如声明 $相当于 jquery
    "allowUmdGlobalAccess": true,
    /* **********************************************************Experimental Options 实验阶段的选项*************************************************/
    // 允许使用装饰器
    "experimentalDecorators": true,
    // 允许使用元数据
    "emitDecoratorMetadata": true,
    /* **********************************************************Advanced Options 高级选项***********************************************************/
    // 跳过声明文件的类型检查
    "skipLibCheck": true,
    // 严格区分文件名的大小写
    "forceConsistentCasingInFileNames": true
  },
  // ts编译和检查的范围
  "include": [
    "src/**/*.ts",
    "src/**/*.d.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "types/**/*.d.ts",
    "types/**/*.ts",
    "build/**/*.ts",
    "build/**/*.d.ts",
    "mock/**/*.ts",
    "vite.config.ts"
  ],
  // ts编译和检查排除的文件或者文件夹
  "exclude": ["node_modules", "dist", "**/*.js"]
}
复制代码

Eslint结合

  1. 安装

    yarn add -D @typescript-eslint/parser @typescript-eslint/eslint-plugin
    复制代码
    • @typescript-eslint/parser: 将ts文件parse,让eslint可以认识ts文件

    • @typescript-eslint/eslint-plugineslint官方针对ts的配置文件

  2. 修改.eslintrc.js

    // .eslintrc.js
      parserOptions: {
        parser: '@typescript-eslint/parser',
        ecmaVersion: 2020,
        sourceType: 'module',
        jsxPragma: 'React',
        ecmaFeatures: {
          jsx: true,
        },
      },
      extends: [
        'plugin:@typescript-eslint/recommended',
      ],
      rules: {
         '@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: '^_',
          },
        ],
      }
    复制代码

    ⚠️ 注意:

    • 要使eslint也能够检查ts文件的话,记得在eslint的检查文件规则上添加tstsx后缀的文件.
    • 同样的,修改eslint配置后,编辑器无法立即识别,需要重启项目让其重新载入配置

EditorConfig

图片转载自

vscode编辑器添加editorconfig插件,然后在项目的根目录中新建.editorconfig,填写你的配置,详细请戳这里。以下提供参考案例:

root = true

[*] charset=utf-8 end_of_line=lf insert_final_newline=true indent_style=space indent_size=2 max_line_length = 100

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

[*.md] trim_trailing_whitespace = false

[Makefile] indent_style = tab

复制代码

Vue

这里只介绍Vue如何配合相关的linter进行使用。

Eslint配合

  • 安装

    yarn add -D eslint-plugin-vue vue-eslint-parser
    复制代码
    • eslint-plugin-vue: vue官方推荐的eslint插件
    • vue-eslint-parser:将.vue文件parseeslint能够识别的文件,对 template<script> 进行解析生成特定的增强的 AST
  • 修改.eslintrc.js

    module.exports = {
       parser: 'vue-eslint-parser',
         extends: [
        'plugin:vue/vue3-recommended',
      ],
      rules: {
        '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/html-self-closing': [
          'error',
          {
            html: {
              void: 'always',
              normal: 'never',
              component: 'always',
            },
            svg: 'always',
            math: 'always',
          },
        ],
      }
    }
    复制代码

    由于prettierstylelint官方已经对vuereact进行内置支持了,这里可以不用再进行其他的操作

  • 修改lint-staged,提交时格式化vue文件

    .husky/linstagedrc.js
    '*.vue': ['eslint --fix', 'prettier --write', 'stylelint --fix'],
    复制代码

React

这里只介绍React如何配合相关的linter进行使用。

Eslint配合

  • 安装
yarn add -D eslint-plugin-react
复制代码
  • .eslintrc.js
  extends: [
    'plugin:react/recommended',
  ],
  settings: {
    react: {
      version: 'detect'
    }
  },
  parserOptions: {
    ecmaVersion: 2020,
    sourceType: 'module', // Allows for the use of imports
    ecmaFeatures: {
      jsx: true // Allows for the parsing of JSX
    }
  },
复制代码

总结

  • 当你要使用的相关的linter时,可以搜索对应的github和官网,按照相关的文档进行操作进行集成。
  • 虽然我们有很多的项目脚手架都会帮我们做好这些,但是,要想真正掌握,还是需要自己去折腾一番
  • 如果遇到相关的配置没有生效的话,可以查找对应的linter的版本,查看对应版本的配置有没有发生变化。或者看看是不是编辑器没有加载的问题。
  • 查看对应的linter,在你使用的框架Vue或者React,用不用配置对应的插件,或者比如webpack用不用配置对应的loader
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享