background

Some of our projects use TSLint to standardize our TypeScript code, and some don’t even have Lint tools for development. Due to performance issues, we use ESLint instead of TSLint. Prettier and hook tools to standardize our submitted code and unify the team’s development style.


Install ESLint and remove TSLint

Since our project configuration may vary, some vue-CLI comes with an ESLint or TSLint installation, and some projects don’t have Lint tools. Package. json

PS: There is a small hole here caused by an ESLint version issuebugSo ESLint limits the version number to 6.5.1

<! -- package. Json related configuration - > {" scripts ": {" format" : "prettier - write \"/SRC / * * * ts \ "\"/SRC / * * *. Vue \ ""," lint ": "eslint --fix --ext .ts,.vue src" }, "husky": { "hooks": { "pre-commit": "lint-staged" } }, "lint-staged": { "src/**/*.{ts,vue}": [ "prettier --write", "eslint --fix" ] }, "devDependencies": {"@typescript-eslint/eslint-plugin": "^2.21.0", "@typescript-eslint/parser": "^2.20.0", "eslint": "^ 6.5.1 eslint - config -", "prettier" : "^ 6.10.0", "eslint - plugin - prettier" : "^ 3.1.2", "eslint - plugin - vue" : "^" 5.2.3 requires, "husky" : "^ holdings", "lint - staged" : "^ 10.0.7", "prettier" : "^ 1.19.1", "vue - eslint - parser" : "^ 7.0.0",}}Copy the code
  • 1. Delete the tslint.json configuration file first

  • 2. Install esLint dependencies

    NPM I -d [email protected] @typescript-eslint/parser @typescript-eslint/eslint-plugin

    @typescript-eslint/parser: typescript-eslint/eslint-plugin: built-in plugins to parse typescript rules

  • Create the.eslintrc.js file

Parser: 'vue-eslint-parser', // parses. Vue file extends: ['plugin:@typescript-eslint/recommended',], plugins: ['@typescript-eslint'], parserOptions: {parser: '@typescript-eslint/parser' // parse.ts files},Copy the code

Note: the parser: ‘vue-eslint-parser’ is different from parseroptions. parser, vue-eslint-parser parses. @typescript-esLint /parser is our custom parser for typescript files, otherwise we won’t validate typescript-related content properly

Install eslint-plugin-vue

The eslint-plugin-vue plugin is used to detect and standardize the style of VUE code

npm i -D eslint-plugin-vue

Then add the configuration and related rules in.eslintrc.js

extends: ['plugin:vue/recommended', // other rules can also be enabled here, such as default vue/essential 'plugin:@typescript-eslint/recommended',], rules: {... }Copy the code

3. Installing Prettier

Prettier uses Prettier as a formatting tool to work better with our ESLint, where dependencies are installed:

npm i -D prettier eslint-config-prettier eslint-plugin-prettier
Copy the code

Eslint-config-prettier: Prettier is preferred when esLint and Prettier configurations conflict

Eslint-plugin-prettier: The use of prettier as the ESLint specification

extends: [ 'plugin:vue/recommended', 'plugin:prettier/recommended', 'prettier/@typescript-eslint', // Preferred prettier style specification 'plugin:@typescript-eslint/recommended',],Copy the code

Prettier is configured as needed, and the.prettierrc file is created

{
  "singleQuote": true,
  "tabWidth": 2,
  "useTabs": false,
  "semi": false,
  "trailingComma": "all",
  "printWidth": 120
}
Copy the code

The entire.eslintrc.js looks like this

module.exports = {
  root: true.env: {
    browser: true.node: true.es6: true,},parser: 'vue-eslint-parser'.extends: [
    'plugin:vue/recommended'.'plugin:prettier/recommended'.'prettier/@typescript-eslint'.'plugin:@typescript-eslint/recommended',].plugins: ['@typescript-eslint'].parserOptions: {
    parser: '@typescript-eslint/parser',},rules: {
    'prettier/prettier': 'error'.'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off'.'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off'.'array-bracket-spacing': 2.'no-var': 2.'no-eval': 2.'arrow-spacing': 2.'block-spacing': 2.'key-spacing': 2.'brace-style': 2.'vue/camelcase': 2.'vue/require-component-is': 0.'vue/require-default-prop': 0.'comma-dangle': [2.'always-multiline'].'vue/eqeqeq': [2.'always', { null: 'ignore'}].'object-curly-spacing': [2.'always'].'vue/singleline-html-element-content-newline': 0.'vue/html-closing-bracket-newline': [
      2,
      {
        singleline: 'never'.multiline: 'always'],},'vue/max-attributes-per-line': 0.'vue/html-self-closing': [
      2,
      {
        html: {
          void: 'always'.normal: 'never'.component: 'always',},svg: 'always'.math: 'always'],},// Set the typescript-eslint rule
    // https://github.com/typescript-eslint/typescript-eslint/tree/master/packages/eslint-plugin/docs/rules
    '@typescript-eslint/camelcase': 0.// Some fields of the buried point cannot be replaced
    '@typescript-eslint/no-non-null-assertion': 0.// Allow non-null assertion operators
    '@typescript-eslint/member-delimiter-style': [
      2,
      {
        multiline: {
          delimiter: 'none'.requireLast: true,},singleline: {
          delimiter: 'semi'.requireLast: false,}},],'@typescript-eslint/no-unused-vars': [0, { args: 'none'}].// TODO late step-up replacement
    '@typescript-eslint/interface-name-prefix': 0.'@typescript-eslint/explicit-function-return-type': 0.'@typescript-eslint/no-empty-function': 0.'@typescript-eslint/no-var-requires': 0.'@typescript-eslint/no-use-before-define': 0.'@typescript-eslint/no-explicit-any': 0.// TODO}},Copy the code

Now that ESLint and Prettier are configured, let’s use tools to format and validate code at git commit. If multiple Vue projects want to reuse configuration items, we can package the ESLint configuration and prettier configuration into a NPM private server package.

Exports = {extends: [require.resolve(' XXX /vue-lint/eslint')],}Copy the code

4. Validation and formatting using Husky and Lint-staged hooks

  • Husky is the hook that controls code submission, where you can do some pre-checking or formatting before committing code to a Git repository.
  • Lint-staged is a front-end file filtering tool (just file filters) that filters file systems so that you don’t have to validate all files per commit.

1. Install HusKY and Lint-staged

npm i -D husky lint-staged
Copy the code

2. Modify package.json to add configuration:

"husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
 },
"lint-staged": {
   "src/**/*.{ts,vue}": [
      "prettier --write",
      "eslint --fix"
   ]
},
Copy the code

Each time, it will only verify that your commit complies with your locally configured ESLint rules before committing locally. If it does, the commit will succeed. If it doesn’t, it will automatically execute esLint-fix to try to fix it for you. If it succeeds, it will commit the fixed code for you, and if it fails, it will prompt you with an error and let you fix the error before you can commit the code.

5. Use commitLint to normalize code commits

Vi. Vscode related configuration

  • The installationESLint, Vertur, PrettierPlugins, if you usestylusIt is recommended to install oneManta's Stylus Supremacy
  • configurationsetting.json
{ "editor.formatOnSave": true, "editor.codeActionsOnSave": { "source.fixAll.eslint": true }, "vetur.format.defaultFormatter.ts": "prettier", "vetur.format.defaultFormatter.js": "prettier", "vetur.format.defaultFormatter.less": "prettier", "vetur.format.defaultFormatter.stylus": "stylus-supremacy", "vetur.format.defaultFormatter.html": "prettyhtml", "vetur.format.defaultFormatterOptions": { "prettyhtml": { "printWidth": 120 } }, "eslint.options": { "extensions": [" js ", "vue", "ts" and "benchmark"]}, / / the following for stylus configuration "stylusSupremacy. InsertColons" : If false, / / insert a colon "stylusSupremacy. InsertSemicolons" : false, whether / / insert points good "stylusSupremacy. InsertBraces" : If false, / / insert braces "stylusSupremacy. InsertNewLineAroundImports" : False, / / import whether "stylusSupremacy. InsertNewLineAroundBlocks" : a new line after false}Copy the code

Setting. json can be directly copied locally, or you can create a.vscode folder in the project and remove.vscode from the.gitignore folder so that teams can share this part of the VScode configuration.

conclusion

If you want to format the global code or validate the global code, you can automatically format and validate the global code before git commit. Instead of putting it on a pre-commit hook and executing it every time git commit takes time, you can write a script in package.json and execute it manually whenever you need it.

"scripts": {
  "format": "prettier --write \"src/**/*.ts\" \"src/**/*.vue\"",
  "lint": "eslint --fix --ext .ts,.vue src"
}
Copy the code

In addition, conflicts caused by version problems of various plug-ins can generally be found in the github Issues of corresponding plug-ins.