【基础】React工程配置(基于Vite配置)

315 阅读8分钟

vite.config.ts 配置

作用

vite.config.tsVite 项目的核心配置文件,用于自定义 Vite 的构建行为、开发服务器设置、插件等。它位于项目根目录,使用 TypeScript 编写(也可以是 vite.config.js)。修改 vite.config.ts 后,不需要重启服务器,Vite 会自动热重载。可以通过 defineConfig 获得类型提示和自动补全。

主要功能

功能类别示例配置说明
开发服务器设置端口、代理、HTTPS、自动打开浏览器等
构建输出输出目录、打包格式、压缩方式等
插件系统加载插件(如 React、Vue、UnoCSS、自动导入等)
路径别名设置 @ 指向 src 目录
环境变量区分开发/生产环境,读取 .env 文件
优化行为分包策略、预构建依赖、CDN 替换等

配置项解释

配置项作用说明
plugins加载插件,如 @vitejs/plugin-react 支持 React
resolve.alias设置路径别名,简化导入路径
server.port设置本地开发服务器端口
server.proxy配置 API 代理,解决跨域问题
build.outDir设置打包输出目录,默认是 dist
build.rollupOptions自定义 Rollup 打包行为,如分包

空React项目默认vite.config.ts

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vite.dev/config/
export default defineConfig({
  // react插件
  plugins: [react()],
})

常用的配置

配置1

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import path from 'path'

export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
    },
  },
  server: {
    port: 3000,
    open: true,
    proxy: {
      '/api': {
        target: 'http://localhost:5000',
        changeOrigin: true,
      },
    },
  },
  build: {
    outDir: 'dist',
    minify: 'terser',
    rollupOptions: {
      output: {
        manualChunks: {
          vendor: ['react', 'react-dom'],
        },
      },
    },
  },
})

package.json配置

package.jsonNode.js / 前端项目的“身份证” ,它用 JSON 格式记录了项目的元数据、依赖、脚本命令等关键信息。
Vite、Create React App(CRA)、Next.js 等所有基于 Node 的工具链都会读取它。

核心字段

字段名作用示例
name项目名称,必须全局唯一(若发布到 npm)"name": "my-react-app"
version当前版本号,遵循 SemVer 规范"version": "1.0.0"
description项目简介,会显示在 npm 搜索页"description": "A demo React app built with Vite"
main入口文件(CommonJS 模块)"main": "dist/index.js"
type指定模块系统:"module" 为 ES Module,"commonjs" 为 CommonJS"type": "module"
scripts自定义命令,如 npm run dev / npm run build见下方示例
dependencies生产依赖(项目运行时必需)"react": "^18.2.0"
devDependencies开发依赖(仅在开发/构建阶段使用)"vite": "^5.0.0"
peerDependencies同伴依赖(插件/库要求宿主项目必须安装)"react": ">=16.8.0"
engines指定 Node / npm 版本限制"node": ">=18"
private设为 true 可防止意外发布到 npm"private": true

常用命令

命令实际运行的脚本作用
npm run devvite启动 Vite 开发服务器
npm run buildtsc && vite build先类型检查,再打包
npm run previewvite preview本地预览构建产物
npm run linteslint ...代码风格检查

配置细节

版本号:^ 与 ~ 的区别

  • "^18.2.0":可升级 18.x.x 的最新补丁或次版本(不跨主版本)。
  • "~18.2.0":只能升级 18.2.x 的最新补丁。
  • 无符号如 "18.2.0":锁定精确版本。

依赖管理

查看依赖树

npm ls

升级依赖

npm update
# 或交互式升级
npx npm-check -u

配置模版

模版1

{
  "name": "my-react-app",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "tsc && vite build",
    "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
    "preview": "vite preview"
  },
  "dependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  },
  "devDependencies": {
    "@types/react": "^18.2.43",
    "@types/react-dom": "^18.2.17",
    "@vitejs/plugin-react": "^4.2.1",
    "eslint": "^8.55.0",
    "typescript": "^5.2.2",
    "vite": "^5.0.8"
  }
}

antd pro项目配置(比较规范)

{
  "name": "ant-design-pro",
  "version": "6.0.0",
  "private": true,
  "description": "An out-of-box UI solution for enterprise applications",
  "repository": "git@github.com:ant-design/ant-design-pro.git",
  "scripts": {
    "analyze": "cross-env ANALYZE=1 max build",
    "biome:lint": "npx @biomejs/biome lint",
    "build": "max build",
    "deploy": "npm run build && npm run gh-pages",
    "dev": "npm run start:dev",
    "gh-pages": "gh-pages -d dist",
    "i18n-remove": "pro i18n-remove --locale=zh-CN --write",
    "postinstall": "max setup",
    "jest": "jest",
    "lint": "npm run biome:lint && npm run tsc",
    "lint-staged": "lint-staged",
    "openapi": "max openapi",
    "prepare": "husky",
    "preview": "npm run build && max preview --port 8000",
    "record": "cross-env NODE_ENV=development REACT_APP_ENV=test max record --scene=login",
    "serve": "umi-serve",
    "start": "cross-env UMI_ENV=dev max dev",
    "start:dev": "cross-env REACT_APP_ENV=dev MOCK=none UMI_ENV=dev max dev",
    "start:devmock": "cross-env REACT_APP_ENV=dev UMI_ENV=dev max dev",
    "start:no-mock": "cross-env MOCK=none UMI_ENV=dev max dev",
    "start:pre": "cross-env REACT_APP_ENV=pre UMI_ENV=dev max dev",
    "start:test": "cross-env REACT_APP_ENV=test MOCK=none UMI_ENV=dev max dev",
    "test": "jest",
    "test:coverage": "npm run jest -- --coverage",
    "test:update": "npm run jest -- -u",
    "tsc": "tsc --noEmit"
  },
  "browserslist": [
    "defaults"
  ],
  "dependencies": {
    "@ant-design/icons": "^5.6.1",
    "@ant-design/pro-components": "^2.7.19",
    "@ant-design/v5-patch-for-react-19": "^1.0.3",
    "@monaco-editor/react": "^4.7.0",
    "antd": "^5.26.4",
    "antd-style": "^3.7.0",
    "classnames": "^2.5.1",
    "dayjs": "^1.11.13",
    "react": "^19.1.0",
    "react-dom": "^19.1.0",
    "vanilla-jsoneditor": "^3.8.0"
  },
  "devDependencies": {
    "@ant-design/pro-cli": "^3.3.0",
    "@biomejs/biome": "^2.0.6",
    "@commitlint/cli": "^19.5.0",
    "@commitlint/config-conventional": "^19.5.0",
    "@testing-library/dom": "^10.4.0",
    "@testing-library/react": "^16.0.1",
    "@types/express": "^5.0.3",
    "@types/jest": "^30.0.0",
    "@types/lodash": "^4.17.10",
    "@types/node": "^24.0.10",
    "@types/react": "^19.1.5",
    "@types/react-dom": "^19.1.5",
    "@types/react-helmet": "^6.1.11",
    "@umijs/max": "^4.3.24",
    "cross-env": "^7.0.3",
    "express": "^4.21.1",
    "gh-pages": "^6.1.1",
    "husky": "^9.1.7",
    "jest": "^30.0.4",
    "jest-environment-jsdom": "^29.7.0",
    "lint-staged": "^16.1.2",
    "mockjs": "^1.1.0",
    "ts-node": "^10.9.2",
    "typescript": "^5.6.3",
    "umi-presets-pro": "^2.0.3",
    "umi-serve": "^1.9.11"
  },
  "engines": {
    "node": ">=20.0.0"
  },
  "packageManager": "pnpm@9.15.4+sha512.b2dc20e2fc72b3e18848459b37359a32064663e5627a51e4c74b2c29dd8e8e0491483c3abb40789cfd578bf362fb6ba8261b05f0387d76792ed6e23ea3b1b6a0"
}

prettierrc代码格式化配置

.prettierrc.json

.prettierrc.json 是 Prettier 的全局格式化规则文件,放在项目根目录即可生效。 它用 JSON 格式声明所有可用的格式化选项,优先级高于 IDE 设置,确保团队代码风格绝对一致。

配置属性

字段类型默认值说明示例
printWidthnumber80单行最大字符数,超过即换行"printWidth": 100
tabWidthnumber2每个缩进级别的空格数"tabWidth": 4
useTabsbooleanfalseTab 还是 空格 缩进"useTabs": false ➜ 空格
semibooleantrue语句末尾是否加分号"semi": false ➜ 去掉分号
singleQuotebooleanfalse字符串使用单引号还是双引号"singleQuote": true
quoteProps"as-needed" | "consistent" | "preserve""as-needed"对象属性名何时加引号"quoteProps": "consistent"
trailingComma"none" | "es5" | "all""es5"多行结构末尾是否加逗号"trailingComma": "all"
bracketSpacingbooleantrue对象字面量 {} 中括号内侧是否保留空格{ foo: 1 } vs {foo: 1}
bracketSameLinebooleanfalseJSX 的 > 是否与最后一行属性同行<div
> vs <div>
arrowParens"always" | "avoid""always"箭头函数参数是否强制括号x => x vs (x) => x
endOfLine"lf" | "crlf" | "cr" | "auto""lf"换行符风格(Unix/Windows)"endOfLine": "lf"
embeddedLanguageFormatting"auto" | "off""auto"是否格式化 markdown / html 中的代码块"off" 可跳过
htmlWhitespaceSensitivity"css" | "strict" | "ignore""css"HTML 空白字符处理方式"ignore" 保留所有空格
jsxSingleQuotebooleanfalseJSX 中字符串使用单引号"jsxSingleQuote": true
proseWrap"always" | "never" | "preserve""preserve"Markdown 文本是否强制换行"always" 按 printWidth 换行

配置示例

{
  "singleQuote": true,
  "semi": false,
  "bracketSpacing": true,
  "htmlWhitespaceSensitivity": "ignore",
  "endOfLine": "auto",
  "trailingComma": "all",
  "tabWidth": 2
}
{
  "printWidth": 100,
  "tabWidth": 2,
  "useTabs": false,
  "semi": true,
  "singleQuote": true,
  "quoteProps": "as-needed",
  "trailingComma": "es5",
  "bracketSpacing": true,
  "bracketSameLine": false,
  "arrowParens": "always",
  "endOfLine": "lf",
  "embeddedLanguageFormatting": "auto",
  "htmlWhitespaceSensitivity": "css",
  "jsxSingleQuote": false,
  "proseWrap": "preserve"
}

.prettierrcignore

配置不对哪些文件进行代码格式化,创建 .prettierignore 排除不想格式化的文件/目录,内容同 .gitignore。

/dist/*
/html/*
.local
/node_modules/**
**/*.svg
**/*.sh
/public/*

与VSCode集成

安装 Prettier 插件 并勾选“保存时格式化”。

cli格式化命令

执行格式化
npx prettier --write .

格式化检查
npx prettier --check .

eslint 规范配置

.eslintrc.ts

.eslintrc.ts 是 ESLint 的配置文件,采用 TypeScript 语法编写(需额外安装 @typescript-eslint/parser)。 它告诉 ESLint:

  • 用哪些规则(rules)
  • 解析什么语法(parser)
  • 继承哪些预设(extends)
  • 忽略哪些文件(ignorePatterns)
  • 支持哪些全局变量(globals)

属性解释

字段用途常见值
roottrue 表示这是根配置,不再向上查找 .eslintrc.*true
env预定义全局变量集合browser, node, es2022, jest
extends继承共享配置(可叠加)eslint:recommended, @typescript-eslint/recommended, prettier
parser指定代码解析器@typescript-eslint/parser, @babel/eslint-parser
parserOptions传给解析器的额外参数ecmaVersion, sourceType: 'module', ecmaFeatures.jsx
plugins加载插件包(提供额外 rules)react, @typescript-eslint, react-hooks, jsx-a11y
rules规则开关与级别`012"off""warn""error"`
settings插件共享数据react.version: 'detect'
ignorePatterns排除文件/目录['dist', 'vite.config.ts']

规则级别

简写全称效果
0 / "off"关闭规则不检查
1 / "warn"警告控制台黄色提示,不会阻断构建
2 / "error"报错控制台红色,CI 可阻断

配置模版

module.exports = {
  root: true, // 指定了root为true,eslint只检查当前项目目录
  env: {
    // 提供预设的全局变量,避免eslint检查报错,例如window
    browser: true,
    node: true,
    es6: true,
  },
  extends: [
    // 继承eslint推荐的检查规则
    'eslint:recommended',
  ],
  parserOptions: {
    ecmaVersion: 'latest', // 指定ECMAScript 语法为最新
    sourceType: 'module', // 指定代码为 ECMAScript 模块
    ecmaFeatures: {
      tsx: true, // 启用tsx
    },
  },
}
// .eslintrc.ts
import { Linter } from 'eslint';

const config: Linter.Config = {
  root: true, // 停止向上查找父级配置
  env: {
    browser: true,
    es2022: true,
    node: true,
  },
  extends: [
    'eslint:recommended',            // ESLint 内置推荐规则
    '@typescript-eslint/recommended', // TS 推荐规则
    'plugin:react/recommended',       // React 推荐规则
    'plugin:react-hooks/recommended', // React Hooks 规则
    'plugin:jsx-a11y/recommended',    // 无障碍规则
    'prettier',                       // 关闭与 Prettier 冲突的规则
  ],
  parser: '@typescript-eslint/parser', // 用 TS 解析器
  parserOptions: {
    ecmaVersion: 'latest',
    sourceType: 'module',
    ecmaFeatures: { jsx: true },      // 支持 JSX
  },
  plugins: ['react', '@typescript-eslint', 'react-hooks', 'jsx-a11y'],
  rules: {
    // 自定义规则:0=off 1=warn 2=error
    'react/react-in-jsx-scope': 0,   // React 17+ 不再需要 import React
    '@typescript-eslint/no-unused-vars': 1,
    'prefer-const': 'error',
    'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'warn',
  },
  settings: {
    react: { version: 'detect' },    // 自动读取 package.json 中的 react 版本
  },
  ignorePatterns: ['dist', 'node_modules', '*.config.{js,ts}'],
};

export default config;

常用cli命令

命令说明
npx eslint src --ext .ts,.tsx手动检查
npx eslint . --fix自动修复可修复的问题
npx eslint . --max-warnings 0任何 warning 也视为 CI 失败

快速安装(React+TS)

npm i -D \
  eslint \
  @typescript-eslint/parser \
  @typescript-eslint/eslint-plugin \
  eslint-plugin-react \
  eslint-plugin-react-hooks \
  eslint-plugin-jsx-a11y \
  eslint-config-prettier

hsky 配置

根目录创建 .hsky 文件夹

pre-commit

commit前检查

lint-staged

commit-msg

commit-msg提交信息检查

npx --no -- commitlint --edit $1

_文件夹

husky.sh

#!/usr/bin/env sh
if [ -z "$husky_skip_init" ]; then
  debug () {
    if [ "$HUSKY_DEBUG" = "1" ]; then
      echo "husky (debug) - $1"
    fi
  }

  readonly hook_name="$(basename -- "$0")"
  debug "starting $hook_name..."

  if [ "$HUSKY" = "0" ]; then
    debug "HUSKY env variable is set to 0, skipping hook"
    exit 0
  fi

  if [ -f ~/.huskyrc ]; then
    debug "sourcing ~/.huskyrc"
    . ~/.huskyrc
  fi

  readonly husky_skip_init=1
  export husky_skip_init
  sh -e "$0" "$@"
  exitCode="$?"

  if [ $exitCode != 0 ]; then
    echo "husky - $hook_name hook exited with code $exitCode (error)"
  fi

  if [ $exitCode = 127 ]; then
    echo "husky - command not found in PATH=$PATH"
  fi

  exit $exitCode
fi