3

We use the popular build tool vite to create the project and choose the react + ts template. About Eslint + Prettier + husky + lint-staged configuration is also applicable to projects created by webpack and Vue, slightly different places will be mentioned below, please feel free to eat.

1. Create a project with vite

 yarn create vite

Enter project name and select react + ts

 success Installed "create-vite@3.0.0" with binaries:
  - create-vite
  - cva
✔ Project name: … my-app
✔ Select a framework: › react
✔ Select a variant: › react-ts
Done. Now run:

  cd my-app
  yarn
  yarn dev

2. Install Eslint

 yarn add -D eslint

3. Initialize configuration Eslint

 npm init @eslint/config

or

 npx exlint --init

3.1. Selection mode:

Check grammar and find problems

 ? How would you like to use ESLint? …
  To check syntax only
❯ To check syntax and find problems
  To check syntax, find problems, and enforce code style

3.2. Select modular syntax:

Select JavaScript modules

 ✔ How would you like to use ESLint? · problems
? What type of modules does your project use? …
❯ JavaScript modules (import/export)
  CommonJS (require/exports)
  None of these

3.3. Select the js framework:

Choose React

 ? Which framework does your project use? …
❯ React
  Vue.js
  None of these

3.4. Whether to use ts

I choose to be

 ? Does your project use TypeScript? › No / Yes

3.5. Select the code running environment

Select browser + node with spaces

 ? Where does your code run? …  (Press <space> to select, <a> to toggle all, <i> to invert selection)
✔ Browser
✔ Node

3.6. Select the configuration file format

choose JavaScript

 ? What format do you want your config file to be in? …
❯ JavaScript
  YAML
  JSON

3.7, install three dependencies

The choice is (eslint resolves the dependencies of react and ts)

 The config that you've selected requires the following dependencies:
eslint-plugin-react@latest 
@typescript-eslint/eslint-plugin@latest 
@typescript-eslint/parser@latest
? Would you like to install them now? › No / Yes

3.8, select the package manager

choose yarn

 ? Which package manager do you want to use? …
  npm
❯ yarn
  pnpm

4. Installation is complete

Generate the .eslintrc.cjs file in the project root directory. This is the file initialized in the above 3 steps. The following configuration is written here.

 // .eslintrc.cjs
module.exports = {
    env: {
        browser: true,
        es2021: true,
        node: true
      },

    extends: "eslint:recommended", //eslint推荐的规则(过于严格)

    parserOptions: {
        ecmaVersion: 'latest',
        sourceType: 'module'
  },
  rules: {

  }
}

5. Continue to install dependencies

Students who use vite install vite-plugin-eslint

 yarn add -D vite-plugin-eslint

Students who use webpack install eslint-webpack-plugin

 yarn add -D eslint-webpack-plugin

The role of the above two dependencies is to automatically check the eslint specification when yarn dev

Install eslint parser @babel/core @babel/eslint-parser

 yarn add -D @babel/core             
yarn add -D @babel/eslint-parser

6. Configure vite.config.js or webpack.config.js

 // vite.config.js
import react from '@vitejs/plugin-react';
import { defineConfig } from 'vite';
import eslintPlugin from 'vite-plugin-eslint';
export default defineConfig({
  plugins: [
    react(),
    eslintPlugin({
      include: ['src/**/*.tsx', 'src/**/*.ts', 'src/*.ts', 'src/*.tsx'], // eslint校验的文件类型
    }),
  ],
});
 // webpack.config.js
const ESLintPlugin = require('eslint-webpack-plugin');

module.exports = {
  // ...
  plugins: [new ESLintPlugin(options)],
  // ...
};

7. Configure eslintrc.cjs

Here we use Tencent's AlloyTeam Eslint
It overrides the rules recommended by eslint and is prettier compatible

 yarn add -D eslint-config-alloy
 // eslintrc.cjs
module.exports = {
  extends: [
    'alloy',
    'alloy/react',
    'alloy/typescript',
  ],
  env: {
    // 你的环境变量(包含多个预定义的全局变量)
    //
    // browser: true,
    // node: true,
    // mocha: true,
    // jest: true,
    // jquery: true
  },
  globals: {
    // 你的全局变量(设置为 false 表示它不允许被重新赋值)
    //
    // myGlobal: false
  },
  rules: {
    // 自定义你的规则
  },
};

8. Install the prettier specification code format

 yarn add -D prettier

After installation, create a .prettierrc.cjs file in the project root directory
AlloyTeam provides a set of Prettier configurations, which are directly inherited.

 // .prettierrc.cjs
module.exports = {
  // 一行最多 120 字符
  printWidth: 120,
  // 使用 2 个空格缩进
  tabWidth: 2,
  // 不使用缩进符,而使用空格
  useTabs: false,
  // 行尾需要有分号
  semi: true,
  // 使用单引号
  singleQuote: true,
  // 对象的 key 仅在必要时用引号
  quoteProps: 'as-needed',
  // jsx 不使用单引号,而使用双引号
  jsxSingleQuote: false,
  // 末尾需要有逗号
  trailingComma: 'all',
  // 大括号内的首尾需要空格
  bracketSpacing: true,
  // jsx 标签的反尖括号需要换行
  bracketSameLine: false,
  // 箭头函数,只有一个参数的时候,也需要括号
  arrowParens: 'always',
  // 每个文件格式化的范围是文件的全部内容
  rangeStart: 0,
  rangeEnd: Infinity,
  // 不需要写文件开头的 @prettier
  requirePragma: false,
  // 不需要自动在文件开头插入 @prettier
  insertPragma: false,
  // 使用默认的折行标准
  proseWrap: 'preserve',
  // 根据显示样式决定 html 要不要折行
  htmlWhitespaceSensitivity: 'css',
  // vue 文件中的 script 和 style 内不用缩进
  vueIndentScriptAndStyle: false,
  // 换行符使用 lf
  endOfLine: 'lf',
  // 格式化嵌入的内容
  embeddedLanguageFormatting: 'auto',
};

9. Configure VScode

Install Eslint plugin, Prettier plugin

 // 配置vscode
// 打开:设置 -> 文本编辑器 -> 字体 -> 在 settings.json 中编辑
// settings.json文件
{
  "files.eol": "\n",
  "editor.tabSize": 2,
 // 保存时将代码按照eslint规则修复
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true,
  },
 // 默认格式化插件
  "editor.defaultFormatter": "esbenp.prettier-vscode",
 // 添加eslint支持
  "eslint.validate": [
    "javascript",
    "javascriptreact",
    "typescript",
    "typescriptreact"
  ] 
}

10. Install and configure husky + lint-staged

Install dependencies

 yarn add -D husky
yarn add -D lint-staged

husky

A tool to add hooks to git clients. After installation, it will automatically add corresponding hooks to the .husky/ directory in the repository; for example, the pre-commit hook will be triggered when you execute git commit. We can implement some operations such as lint checking, unit testing, and code beautification in pre-commit.

package.json needs to add prepare script

 {
  "scripts": {
    "prepare": "husky install"
  }
}

After doing the above work, you can use husky to create a hook

 npx husky add .husky/pre-commit "npx lint-staged"

lint-staged

A tool that only filters out Git code staging area files (files added by git); this is very practical, because if we check the code of the entire project, it may take a long time. If it is an old project, we need to check the previous project. If you do a code specification check and modify the code, this may be troublesome and may lead to great changes to the project. So this lint-staged is a good tool for team projects and open source projects, it is a specification and constraint on the code that individuals want to submit.

At this point, we have implemented monitoring Git hooks. Next, we need to use Lint-staged in the pre-commit hook to perform automatic prettier repairs and ESLint checks on the code. If any files that do not meet the code specifications are found, the commit will be exited directly.

And Lint-staged will only check the code in the Git staging area (the code of git add) instead of the full code, and will automatically add the prettier-formatted code to this commit.

Configure in package.json

 {
 "husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
  "lint-staged": {
    "*.{ts,tsx,js}": [
      "eslint --fix",
      "prettier --write",
      "git add"
    ]
  },
}

For the constraints of commit-msg, because different companies have their own specifications, this article does not configure them for the time being.
In summary, a complete set of Eslint + Prettier + husky + lint-staged front-end code workflow is done.


Kev1n
5 声望2 粉丝