手把手教你搭建React+Vite+TypeScript+prettier+eslint+stylelint+husky+lint-staged前端项目

840 阅读3分钟

使用vite创建react项目

yarn create vite

然后根据提示选择react和typescript

配置Prettier

安装 Prettier 依赖

yarn add -D prettier eslint-config-prettier eslint-plugin-prettier

根目录下新建配置文件.prettierrc.cjs。

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

配置eslint

npm i -D eslint
npx eslint --init

根据提示选择react、typescipt、模块化(import、export)

补齐react-hooks相关的lint

使用react官方给出了hooks的lint插件

yarn add -D eslint-plugin-react-hooks

React17之后使用JSX不需要在引入React,关闭规则

"react/jsx-uses-react": "off",
"react/react-in-jsx-scope": "off"
module.exports = {
  env: {
    browser: true,
    es2021: true,
  },
  extends: [
    'eslint:recommended',
    'plugin:react/recommended',
    'plugin:@typescript-eslint/recommended',
    'plugin:react-hooks/recommended',
    'prettier',
    'plugin:prettier/recommended',
  ],
  overrides: [],
  parser: '@typescript-eslint/parser',
  parserOptions: {
    ecmaFeatures: {
      jsx: true,
    },
    ecmaVersion: 'latest',
    sourceType: 'module',
  },
  plugins: ['react', '@typescript-eslint', 'prettier'],
  rules: {
    'no-var': 'error',
    'no-undef': 'off',
    'prettier/prettier': 'error',
    'react/jsx-uses-react': 'off',
    'react/react-in-jsx-scope': 'off',
    'react/jsx-no-target-blank': 'off',
  },
};

配置stylelint

安装

yarn add -D stylelint stylelint-config-standard

保证css属性顺序

yarn add -D stylelint-order

保证格式化less文件

yarn add -D postcss-less

.stylelintrc.cjs

module.exports = {
  extends: ['stylelint-config-standard'],
  plugins: ['stylelint-order'],
  custonSyntax: 'postcss-less',
  rules: {
    indentation: [
      4,
      {
        severity: 'warning',
      },
    ],
    'no-descending-specificity': null,
    // 属性的排序
    'order/properties-order': [
      'position',
      'top',
      'right',
      'bottom',
      'left',
      'z-index',
      'display',
      'justify-content',
      'align-items',
      'float',
      'clear',
      'overflow',
      'overflow-x',
      'overflow-y',
      'margin',
      'margin-top',
      'margin-right',
      'margin-bottom',
      'margin-left',
      'border',
      'border-style',
      'border-width',
      'border-color',
      'border-top',
      'border-top-style',
      'border-top-width',
      'border-top-color',
      'border-right',
      'border-right-style',
      'border-right-width',
      'border-right-color',
      'border-bottom',
      'border-bottom-style',
      'border-bottom-width',
      'border-bottom-color',
      'border-left',
      'border-left-style',
      'border-left-width',
      'border-left-color',
      'border-radius',
      'padding',
      'padding-top',
      'padding-right',
      'padding-bottom',
      'padding-left',
      'width',
      'min-width',
      'max-width',
      'height',
      'min-height',
      'max-height',
      'font-size',
      'font-family',
      'font-weight',
      'text-align',
      'text-justify',
      'text-indent',
      'text-overflow',
      'text-decoration',
      'white-space',
      'color',
      'background',
      'background-position',
      'background-repeat',
      'background-size',
      'background-color',
      'background-clip',
      'opacity',
      'filter',
      'list-style',
      'outline',
      'visibility',
      'box-shadow',
      'text-shadow',
      'resize',
      'transition',
    ],
  },
};

vscode 配置

安装stylelint插件

配置settings.json

  1. 点击命令面板

  1. 输入settings.json,点击用户设置

  1. 添加下面的配置
"editor.codeActionsOnSave": {
  "source.fixAll": true,
  "source.fixAll.stylelint": true,
},

husky + commitlint + lint-staged

安装配置husky

Husky 是一款 Git Hooks 工具,可以在执行特定的 git 命令时(如: git commit, git push)触发对应的脚本

1. 安装husky

yarn add -D husky
npm set-script prepare "husky install"
yarn prepare

2. pre-commit

在commit之前执行一次lint-staged

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

3. commit-msg

我们可以通过commit-msg钩子处理git提交信息的规范性

yarn add -D commitlint @commitlint/config-conventional
npx husky add .husky/commit-msg 'npx --no-install commitlint --edit "$1"'

@commitlint/config-conventional是「Angular」的提交规范

module.exports = {
  extends: ['@commitlint/config-conventional'],
  rules: {
    'type-enum': [
      2,
      'always',
      [
        'init', // 初始化
        'feat', // 新功能(feature)
        'bug', // 此项特别针对bug号,用于向测试反馈bug列表的bug修改情况
        'fix', // 修补bug
        'ci', // 对ci配置文件和脚本的修改
        'docs', // 文档(documentation)
        'style', // 格式(不影响代码运行的变动)
        'perf', // 性能优化
        'refactor', // 重构(即不是新增功能,也不是修改bug的代码变动)
        'test', // 增加测试
        'chore', // 构建过程或辅助工具的变动
        'revert', // feat(pencil): add ‘graphiteWidth’ option (撤销之前的commit)
        'build', // 打包
      ],
    ],
  },
};

但是由于我们的提交的信息是加了emoji的:

  1. 安装commitlint-config-gitmoji
yarn add -D commitlint-config-gitmoji
  1. 配置
module.exports = {
  extends: ['gitmoji'],
  rules: {
    'type-enum': [
      2,
      'always',
      [
        'init', // 初始化
        'feat', // 新功能(feature)
        'bug', // 此项特别针对bug号,用于向测试反馈bug列表的bug修改情况
        'fix', // 修补bug
        'ci', // 对ci配置文件和脚本的修改
        'docs', // 文档(documentation)
        'style', // 格式(不影响代码运行的变动)
        'perf', // 性能优化
        'refactor', // 重构(即不是新增功能,也不是修改bug的代码变动)
        'test', // 增加测试
        'chore', // 构建过程或辅助工具的变动
        'revert', // feat(pencil): add ‘graphiteWidth’ option (撤销之前的commit)
        'build', // 打包
      ],
    ],
  },
};

安装配置lint-staged

在提交的代码的时候,可以通过 ESLint、Prettier 等工具来格式化代码

但如果直接处理全部代码,首先是可能存在性能问题,其次是可能会修改掉别的同事的代码

这时可以引入 lint-staged,它可以过滤出 Git 代码暂存区文件,这样就不会影响到未更改的文件

1. 安装lint-staged

yarn add -D lint-staged

2. 配置lint-staged

在根目录下配置.lintstagedrc文件

{
  "*.{js,jsx,ts,tsx}": ["npx prettier --write", "npx eslint --fix"],
  "*.{css,less,scss}": ["npx prettier --write", "npx stylelint --fix"],
  "*.{json,md}": ["npx prettier --write"]
}

安装配置commit助手

我们可以配置commit助手,帮助实现一致的提交消息,这里选择的是cz-customizable

安装

yarn add -D cz-customizable

添加命令

"commit": "./node_modules/cz-customizable/standalone.js"

添加配置

  1. 创建.cz-config.cjs文件
module.exports = {
  types: [
    {
      value: ':sparkles: feat',
      name: '✨ feat:     新功能',
    },
    {
      value: ':bug: fix',
      name: '🐛 fix:      修复bug',
    },
    {
      value: ':tada: init',
      name: '🎉 init:     初始化',
    },
    {
      value: ':pencil2: docs',
      name: '✏️  docs:     文档变更',
    },
    {
      value: ':lipstick: style',
      name: '💄 style:    代码的样式美化',
    },
    {
      value: ':recycle: refactor',
      name: '♻️  refactor: 重构',
    },
    {
      value: ':zap: perf',
      name: '⚡️ perf:     性能优化',
    },
    {
      value: ':white_check_mark: test',
      name: '✅ test:     测试',
    },
    {
      value: ':rewind: revert',
      name: '⏪️ revert:   回退',
    },
    {
      value: ':package: build',
      name: '📦️ build:    打包',
    },
    {
      value: ':rocket: chore',
      name: '🚀 chore:    构建/工程依赖/工具',
    },
    {
      value: ':construction_worker: ci',
      name: '👷 ci:       CI related changes',
    },
  ],
  scopes: [
    ['components', '组件相关'],
    ['hooks', 'hook 相关'],
    ['utils', 'utils 相关'],
    ['element-ui', '对 element-ui 的调整'],
    ['styles', '样式相关'],
    ['deps', '项目依赖'],
    ['auth', '对 auth 修改'],
    ['other', '其他修改'],
    // 如果选择 custom,后面会让你再输入一个自定义的 scope。也可以不设置此项,把后面的 allowCustomScopes 设置为 true
    ['custom', '以上都不是?我要自定义'],
  ].map(([value, description]) => {
    return {
      value,
      name: `${value.padEnd(30)} (${description})`,
    };
  }),
  messages: {
    type: '请选择提交类型(必填)',
    customScope: '请输入文件修改范围(可选)',
    subject: '请简要描述提交(必填)',
    body: '请输入详细描述(可选)',
    breaking: '列出任何BREAKING CHANGES(可选)',
    footer: '请输入要关闭的issue(可选)',
    confirmCommit: '确定提交此说明吗?',
  },
  allowCustomScopes: true,
  allowBreakingChanges: [':sparkles: feat', ':bug: fix'],
  subjectLimit: 72,
};

前面也说到我们的commit信息是带有emoji的,这里的表情都是用的 gitmoji 里提供的表情

  1. 配置package.json
"config": {
  "cz-customizable": {
    "config": ".cz-config.cjs"
  }
}

参考

commit规范使用gitmoji全流程 cz-customizable+commitlint+husky+conventional-changelog

commit规范+commitlint+CHANGELOG自动生成一条龙服务

从 0 开始手把手带你搭建一套规范的 Vue3.x 项目工程环境