关于前端工程化:超详细一次搞定Eslint-Prettier-husky-lintstaged前端代码工作流

30次阅读

共计 4745 个字符,预计需要花费 12 分钟才能阅读完成。

咱们应用热门构建工具 vite 创立我的项目,并抉择 react + ts 模板。对于 Eslint + Prettier + husky + lint-staged 配置同样实用于 webpack、Vue 创立的我的项目,稍有不同的中央下文会提到,请释怀食用。

1、应用 vite 创立我的项目

yarn create vite

输出我的项目名并抉择 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、装置 Eslint

yarn add -D eslint

3、初始化配置 Eslint

npm init @eslint/config

或者

npx exlint --init

3.1、抉择模式:

选查看语法并发现问题

? 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、抉择模块化语法:

选 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、抉择 js 框架:

选 React

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

3.4、是否应用 ts

我抉择是

? Does your project use TypeScript? › No / Yes

3.5、抉择代码运行环境

用空格选中 browser + node

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

3.6、抉择配置文件格式

选 JavaScript

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

3.7、装置三个依赖

抉择是(eslint 解析 react 和 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、抉择包管理器

抉择 yarn

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

4、装置实现

在我的项目根目录生成.eslintrc.cjs 文件
这里就是下面 3 步骤初始化的文件, 前面的配置都写这里

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

    extends: "eslint:recommended", //eslint 举荐的规定(过于严格)parserOptions: {
        ecmaVersion: 'latest',
        sourceType: 'module'
  },
  rules: {}}

5、持续装置依赖

应用 vite 的同学装置 vite-plugin-eslint

yarn add -D vite-plugin-eslint

应用 webpack 的同学装置 eslint-webpack-plugin

yarn add -D eslint-webpack-plugin

以上两个依赖的作用都是在 yarn dev 时主动查看 eslint 标准

装置 eslint 解析器 @babel/core @babel/eslint-parser

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

6、配置 vite.config.js 或 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、配置 eslintrc.cjs

此处咱们应用腾讯的 AlloyTeam Eslint
它会笼罩 eslint 举荐的规定,并且兼容 prettier

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、装置 prettier 标准代码格局

yarn add -D prettier

装置后在我的项目根目录创立.prettierrc.cjs 文件
AlloyTeam 提供了一套 Prettier 配置,此配置间接继承。

// .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、配置 VScode

装置 Eslint 插件、Prettier 插件

// 配置 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、装置并配置 husky + lint-staged

装置依赖

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

husky

一个为 git 客户端减少 hook 的工具。装置后,它会主动在仓库中的 .husky/ 目录下减少相应的钩子;比方 pre-commit 钩子就会在你执行 git commit 的触发。咱们能够在 pre-commit 中实现一些比方 lint 查看、单元测试、代码丑化等操作。

package.json 须要增加 prepare 脚本

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

做完以上工作,就能够应用 husky 创立一个 hook 了

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

lint-staged

一个仅仅过滤出 Git 代码暂存区文件 (被 git add 的文件) 的工具;这个很实用,因为咱们如果对整个我的项目的代码做一个查看,可能耗时很长,如果是老我的项目,要对之前的代码做一个代码标准查看并批改的话,这可能就麻烦了,可能导致我的项目改变很大。所以这个 lint-staged,对团队我的项目和开源我的项目来说,是一个很好的工具,它是对集体要提交的代码的一个标准和束缚。

此时咱们曾经实现了监听 Git hooks,接下来咱们须要在 pre-commit 这个 hook 应用 Lint-staged 对代码进行 prettier 的自动化修复和 ESLint 的查看,如果发现不合乎代码标准的文件则间接退出 commit。

并且 Lint-staged 只会对 Git 暂存区 (git add 的代码) 内的代码进行查看而不是全量代码,且会主动将 prettier 格式化后的代码增加到此次 commit 中。

在 package.json 中配置

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

对于 commit-msg 的束缚,因为不同公司有各自的标准,本文暂不配置。
综上,一套残缺的 Eslint + Prettier + husky + lint-staged 前端代码工作流就搞定了。

正文完
 0