保姆级教学——React+Ts +Vite标准化框架搭建
「这是我参与2022首次更文挑战的第3天,活动详情查看:2022首次更文挑战」。
前言
大家好今天由我来给大家搭建一个React+Ts +Vite的标准化框架。在日常开发中我们大多数时间都在维护老项目,但偶尔也会需要自己搭建框架。当我们需要为团队搭建一个React项目时,我觉得参考这篇文章就够了。
项目初始化
创建vite(构建工具)项目
兼容性注意 Vite 需要 Node.js 版本 >= 12.0.0 Node.js 最新版本
使用 Yarn
yarn create @vitejs/app
使用 NPM
npm init @vitejs/app
执行完命令后我们需要选择模板,这边我们选择React

是否是TS我们选择是

查看目录
使用VSCode打开项目我们可以看到基本的构成

启动项目
cd [你的项目名称路径]
yarn 或 npm install
yarn dev
可以看到启动的特别快

访问项目
浏览器访问http://localhost:3000/便可到达我们项目的主页。

配置Typescript
Typescript的文件位置

tsconfig.json
{
  "compilerOptions": {
    "target": "es5", // 指定 ECMAScript 版本
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ], // 要包含在编译中的依赖库文件列表
    "allowJs": true, // 允许编译 JavaScript 文件
    "skipLibCheck": true, // 跳过所有声明文件的类型检查
    "esModuleInterop": true, // 禁用命名空间引用 (import * as fs from "fs") 启用 CJS/AMD/UMD 风格引用 (import fs from "fs")
    "allowSyntheticDefaultImports": true, // 允许从没有默认导出的模块进行默认导入
    "strict": true, // 启用所有严格类型检查选项
    "forceConsistentCasingInFileNames": true, // 不允许对同一个文件使用不一致格式的引用
    "module": "esnext", // 指定模块代码生成
    "moduleResolution": "node", // 使用 Node.js 风格解析模块
    "resolveJsonModule": true, // 允许使用 .json 扩展名导入的模块
    "noEmit": true, // 不输出(意思是不编译代码,只执行类型检查
    "jsx": "react", // 在.tsx文件中支持JSX
    "sourceMap": true, // 生成相应的.map文件
    "declaration": true, // 生成相应的.d.ts文件
    "noUnusedLocals": true, // 报告未使用的本地变量的错误
    "noUnusedParameters": true, // 报告未使用参数的错误
    "experimentalDecorators": true, // 启用对ES装饰器的实验性支持
    "incremental": true, // 通过从以前的编译中读取/写入信息到磁盘上的文件来启用增量编译
    "noFallthroughCasesInSwitch": true 
  },
  "include": [
    "src/**/*" // *** TypeScript文件应该进行类型检查 ***
  ],
  "exclude": ["node_modules", "build"] // *** 不进行类型检查的文件 ***}
大家可以去除注释后放到文件中或者参考自己公司规范。(不懂Typescript?可以参考我这篇文章《一篇文章带你了解Typescript那些事儿》)
项目配置
我们找到 vite.config.ts

vite.config.ts
import { defineConfig } from "vite";
import reactRefresh from "@vitejs/plugin-react-refresh";
import * as path from "path";
// https://vitejs.dev/config/
export default defineConfig({
  plugins: [reactRefresh()],
  // 配置路径别名
      resolve: {
        alias: {
          "@": path.resolve(__dirname, "src"),
        },
      },
    server: {
        port: 3000,
        proxy: {
          "/api": {
            target: "https://yourBaseUrl",
            changeOrigin: true,
            cookieDomainRewrite: "",
            secure: false,
          },
        },
      },
});
我们这边配置路径别名后接口代理
Eslint 配置
ESLint 是一个开源的JavaScript验证工具,可以让我们在编译时就发现我们代码的错误。
安装eslint
npm install eslint -g
安装eslint-plugin-react(不用加-g)
npm install eslint-plugin-react
安装babel-eslint
如果用到了es6的新语法, 需要安装babel-eslint,不然会把箭头函数识别成错误
npm install babel-eslint
.eslintrc.json配置
在项目的根目录创建配置文件.eslintrc.json

eslint会根据.eslintrc.json定义的规则进行代码检测(在mac中的.开头的文件为隐藏文件);
eslint官方给出的一些有关react配置的文档
.eslintrc.json
{
  //文件名 .eslintrc.json
  "env": {
    "browser": true,
    "es6": true,
    "node": true,
    "commonjs": true
  },
  "extends": "eslint:recommended",
  "installedESLint": true,
  "parserOptions": {
    "ecmaFeatures": {
      "experimentalObjectRestSpread": true,
      "jsx": true,
      "arrowFunctions": true,
      "classes": true,
      "modules": true,
      "defaultParams": true
    },
    "sourceType": "module"
  },
  "parser": "babel-eslint",
  "plugins": ["react"],
  "rules": {
    "linebreak-style": ["error", "unix"],
    //"semi": ["error", "always"],
    "no-empty": 0,
    "comma-dangle": 0,
    "no-unused-vars": 0,
    "no-console": 0,
    "no-const-assign": 2,
    "no-dupe-class-members": 2,
    "no-duplicate-case": 2,
    "no-extra-parens": [2, "functions"],
    "no-self-compare": 2,
    "accessor-pairs": 2,
    "comma-spacing": [
      2,
      {
        "before": false,
        "after": true
      }
    ],
    "constructor-super": 2,
    "new-cap": [
      2,
      {
        "newIsCap": true,
        "capIsNew": false
      }
    ],
    "new-parens": 2,
    "no-array-constructor": 2,
    "no-class-assign": 2,
    "no-cond-assign": 2
  }
}
大家也可以参考公司规范。
.eslintignore(eslint忽略配置)
eslint忽略配置,根目录新建文件.eslintignore

.eslintignore
*.sh 
node_modules 
*.md 
*.woff 
*.ttf 
.vscode 
.idea 
dist 
/public 
/docs 
.husky 
.local 
/bin
Prettier
Prettier用于统一团队代码格式化管理。
安装Prettier
npm i prettier -D
在根目录新建一个.prettierrc.js

.prettierrc.js
module.exports = {
  singleQuote: true,
  htmlWhitespaceSensitivity: 'ignore',
  printWidth: 400,
  tabWidth: 2,
  bracketSpacing: true,
  jsxBracketSameLine: false,
}
大家可以参考各自公司的规范或者参考我的这篇文章《使用Prettier统一团队代码》。
stylelint
StyleLint是『一个强大的、现代化的 CSS 检测工具』, 与 ESLint 类似, 是通过定义一系列的编码风格规则帮助我们避免在样式表中出现错误。
安装
npm install --save-dev stylelint@9.1.3
npm install --save-dev stylelint-processor-styled-components
npm install --save-dev stylelint-config-styled-components
npm install --save-dev stylelint-config-recommended
npm install --save-dev stylelint-order
配置
在根目录下新建配置文件.stylelintrc

.stylelintrc
{
  "processors": ["stylelint-processor-styled-components"],
  "extends": [
    "stylelint-config-recommended",
    "stylelint-config-styled-components"
  ],
  "plugins": ["stylelint-order"],
  "rules": {
    "order/order": [
      "declarations",
      "custom-properties",
      "dollar-variables",
      "rules",
      "at-rules"
    ],
}
husky
husky可以检测代码是否合格、样式是否合格、commit信息是否合格  ,husky支持所有的git hooks。
安装
npm i pretty-quick husky @commitlint/cli @commitlint/config-conventional -D
package.json 配置
package.json中新增以下代码
{
"scripts": {
    "install:husky": "husky install",
    "lint:pretty": "pretty-quick --staged",
    "lint:stylelint": "stylelint --fix \"**/*.{tsx,less,postcss,css,scss}\" --cache --cache-location node_modules/.cache/stylelint/",
    "lint:all": "npm run lint:eslint && npm run lint:stylelint"
  }
}
husky初始化
注:根目录必须拥有
.git文件夹
npx husky install
运行脚本后出现.husky文件夹.

完善husky
在.husky文件下新建这么几个文件:commit-msg、common.sh、pre-commit.

commit-msg
// .husky/commit-msg
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npx --no-install commitlint --edit "$1"
common.sh
// .husky/common.sh
command_exists () {
  command -v "$1" >/dev/null 2>&1
}
if command_exists winpty && test -t 1; then
  exec < /dev/tty
fi
pre-commit
// .husky/pre-commit
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
. "$(dirname "$0")/common.sh"
[ -n "$CI" ] && exit 0
yarn run lint:pretty
commitlint.config.js配置
commitlint.config.js配置,是用来规范化提交的信息。
commitlint.config.js
// commitlint.config.js
module.exports = {
  // ↓忽略包含init的提交消息
  ignores: [(commit) => commit.includes('init')],
  // ↓按照传统消息格式来验证
  extends: ['@commitlint/config-conventional'],
  // 自定义解析器
  parserPreset: {
    // 解析器配置
    parserOpts: {
      // commit 提交头的规则限制
      headerPattern: /^(\w*|[\u4e00-\u9fa5]*)(?:[\(\(](.*)[\)\)])?[\:\:] (.*)/,
      // 匹配分组
      headerCorrespondence: ['type', 'scope', 'subject'],
      // 引用
      referenceActions: [
        'close',
        'closes',
        'closed',
        'fix',
        'fixes',
        'fixed',
        'resolve',
        'resolves',
        'resolved',
      ],
      // 对应issue要携带#符号
      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以空白行开头
    'body-leading-blank': [2, 'always'],
    // ↓footer以空白行开头
    'footer-leading-blank': [1, 'always'],
    // ↓header的最大长度
    'header-max-length': [2, 'always', 108],
    // ↓subject为空
    'subject-empty': [2, 'never'],
    // ↓type为空
    'type-empty': [2, 'never'],
    // ↓type的类型
    'type-enum': [
      2,
      'always',
      [
        'feat',
        'fix',
        'perf',
        'style',
        'docs',
        'test',
        'refactor',
        'build',
        'ci',
        'chore',
        'revert',
        'wip',
        'workflow',
        'types',
        'release',
        'update',
      ],
    ],
  },
}
运行 git commit -m 'msg'就可以进行提交前校验了。

VSCode插件安装
- 
JavaScript (ES6) code snippets:使编辑器支持ES6语法。
 - 
Prettier-Code formatter:prettier的格式化插件。
 - 
Eslint:eslint的插件。
 - 
Stylelint:样式文件格式化插件。
 - 
JavaScript and TypeScript Nightly:起用ts最新语法。
 
项目地址与资料参考
以上代码项目地址:项目地址
需要搭建Vue3框架的可以参考三心哥这篇文章:《「保姆式教学」如何搭建一个符合标准的Vue3 + Ts + Vite脚手架?》
大家有什么问题欢迎评论哦~如果你觉得小凌写的不错那么请给小凌一个赞呗。你的支持是我前进下去的动力🙂
转载自:https://juejin.cn/post/7059236538923614216