Vite6+TypeScript+React+ESLint9+Prettier企业级项目配置实战指南

张开发
2026/4/17 10:28:29 15 分钟阅读

分享文章

Vite6+TypeScript+React+ESLint9+Prettier企业级项目配置实战指南
1. 为什么选择Vite6TypeScriptReact技术栈如果你最近查看过React官方文档会发现React19的文档中已经将Vite作为官方推荐的构建工具。而在React18时代Vite尚未成为React的主力构建工具。尽管Vite诞生时间相对较短但它凭借极快的构建速度迅速获得关注成为现代Web开发领域一个极具潜力的选择。Vite的核心优势在于其原生ESMES Modules支持和极快的冷启动速度。我实测过一个中型项目使用Webpack需要近10秒的启动时间而Vite仅需不到1秒。这种差异在大型项目中会更加明显。对于企业级项目来说这种开发体验的提升能显著提高团队效率。1.1 模板选择策略Vite官方提供了两种ReactTypeScript模板react-ts基于Babel或TypeScript编译器(TSC)react-swc-ts基于SWC(Rust编写的编译器)1.1.1 性能对比SWC的优势主要体现在构建速度显著更快特别是大型项目内存占用更低热更新速度更快我曾在公司内部一个包含300组件的中型项目中进行测试SWC的构建速度比传统Babel方案快约40%。1.1.2 开发者体验react-ts提供了完整的类型系统和错误提示而SWC虽然快速但可能缺少一些高级类型特性。如果你的团队更注重开发体验和类型安全react-ts可能是更好选择。1.1.3 推荐场景根据项目特点选择新项目且团队规模较小注重开发体验和类型安全不追求极致的构建速度 → 推荐使用react-ts如果是大型复杂项目需要快速的开发反馈循环CI/CD构建时间敏感 → 推荐使用react-swc-ts1.2 创建项目建议使用pnpm管理依赖它能很好地解决幽灵依赖问题。执行以下命令创建项目pnpm create vite my-app --template react-swc-ts初始化后的项目结构非常简洁与Vue脚手架创建的项目相比React的初始配置要简单得多。2. 代码质量与格式的统一在企业级项目中保持代码风格一致至关重要。我们将配置ESLint9和Prettier来实现这一目标。2.1 配置ESLint9注意ESLint v9.0.0开始配置文件格式已变更不再使用.eslintrc.cjs而是eslint.config.js。2.1.1 扁平化配置ESLint9引入了扁平化配置方式配置对象是一个数组export default [ { 配置对象 }, 扩展插件1, { 扩展插件1的配置对象 }, 扩展插件2, { 扩展插件2的配置对象 } ]重要配置属性files指定配置应用的文件ignores指定忽略的文件plugins定义可用的规则rules包含已配置的规则2.1.2 安装插件React初始化的框架插件较少我们需要安装一些增强配置pnpm add -D eslint-plugin-react-x eslint-plugin-react-dom2.1.3 修改eslint.config.js完整配置示例import js from eslint/js; import globals from globals; import reactHooks from eslint-plugin-react-hooks; import reactRefresh from eslint-plugin-react-refresh; import tseslint from typescript-eslint; import reactX from eslint-plugin-react-x; import reactDom from eslint-plugin-react-dom; import prettierPlugin from eslint-plugin-prettier; import prettierConfig from eslint-config-prettier; export default tseslint.config( { ignores: [dist] }, { extends: [ js.configs.recommended, ...tseslint.configs.recommendedTypeChecked, prettierConfig, ], files: [**/*.{ts,tsx}], languageOptions: { ecmaVersion: 2020, globals: globals.browser, parserOptions: { project: [./tsconfig.node.json, ./tsconfig.app.json], tsconfigRootDir: import.meta.dirname, }, }, plugins: { react-hooks: reactHooks, react-refresh: reactRefresh, react-x: reactX, react-dom: reactDom, prettier: prettierPlugin, }, rules: { ...reactHooks.configs.recommended.rules, react-refresh/only-export-components: [warn, { allowConstantExport: true }], ...reactX.configs[recommended-typescript].rules, ...reactDom.configs.recommended.rules, prettier/prettier: error, no-console: off, no-debugger: off, max-len: off, no-multi-spaces: off, no-return-assign: off, semi: off, eqeqeq: error, jsx-quotes: off, import/prefer-default-export: off, import/extensions: off, import/no-unresolved: off, no-multiple-empty-lines: off, no-param-reassign: off, typescript-eslint/no-shadow: off, typescript-eslint/no-explicit-any: off, typescript-eslint/no-unused-vars: warn, typescript-eslint/ban-ts-comment: off, typescript-eslint/indent: off, typescript-eslint/no-empty-object-type: off, }, } );2.2 配置Prettier安装必要依赖pnpm add -D prettier eslint-plugin-prettier eslint-config-prettier创建.prettierrc.json文件{ semi: true, tabWidth: 2, singleQuote: true, printWidth: 150, bracketSpacing: true, arrowParens: always, endOfLine: lf, trailingComma: all, bracketSameLine: false, embeddedLanguageFormatting: auto, useTabs: false, htmlWhitespaceSensitivity: ignore }在package.json中添加格式化脚本{ scripts: { format: prettier --write src/ } }如果使用VSCode建议安装Prettier插件并启用Format On Save功能。3. TypeScript配置优化3.1 配置文件区别Vite项目中有三个TypeScript配置文件tsconfig.json顶层的TypeScript配置文件tsconfig.app.json前端应用代码配置tsconfig.node.jsonNode脚本/配置文件的配置这种分离可以避免前端代码和Node脚本的类型冲突提高类型检查的准确性。3.2 调整TypeScript配置修改tsconfig.app.json{ compilerOptions: { tsBuildInfoFile: ./node_modules/.tmp/tsconfig.app.tsbuildinfo, target: ES2020, useDefineForClassFields: true, lib: [ES2020, DOM, DOM.Iterable], module: ESNext, skipLibCheck: true, moduleResolution: bundler, allowImportingTsExtensions: true, verbatimModuleSyntax: true, moduleDetection: force, noEmit: true, jsx: react-jsx, strict: true, noUnusedLocals: true, noUnusedParameters: true, erasableSyntaxOnly: true, noFallthroughCasesInSwitch: true, noUncheckedSideEffectImports: true, baseUrl: ., paths: { /*: [src/*] } }, include: [src, src/*], exclude: [node_modules] }4. 代码检查器配置vite-plugin-checker是一个能在工作流程中运行TypeScript、ESLint等检查工具的Vite插件。安装pnpm add vite-plugin-checker -D修改vite.config.tsimport { defineConfig } from vite; import react from vitejs/plugin-react-swc; import checker from vite-plugin-checker; export default defineConfig({ plugins: [ react(), checker({ typescript: true, eslint: { useFlatConfig: true, lintCommand: eslint ./src/**/*.{ts,tsx,js,jsx}, }, terminal: true, }), ], });5. 路由配置安装react-router-dompnpm add react-router-dom创建路由文件src/router/index.tsximport { lazy } from react; import { createHashRouter, Navigate } from react-router-dom; import type { RouteObject } from react-router-dom; import Layout from /components/Layout/Index.tsx; type NewRouteObject OmitRouteObject, children { icon?: string; treeCode?: string; children?: NewRouteObject[]; }; const Index lazy(() import(/pages/Index/Index.tsx)); const About lazy(() import(/pages/About/Index.tsx)); export const List: NewRouteObject[] [ { path: /, element: Layout /, children: [ { index: true, path: /, treeCode: home, element: Index /, }, { path: /about, treeCode: aboutUs, element: About /, }, ], }, { path: *, element: Navigate to/ replace /, }, ]; const routes createHashRouter(List as RouteObject[]); export default routes;6. 状态管理工具配置6.1 Zustand配置安装pnpm add zustand创建状态存储src/store/index.tsimport { create } from zustand; export type State { count: number; dispatch: (action: Action) void; }; export type Actions { increment: (qty: number) void; decrement: (qty: number) void; }; export type Action { type: keyof Actions; qty: number; }; const countReducer (state: State, action: Action) { switch (action.type) { case increment: return { count: state.count action.qty }; case decrement: return { count: state.count - action.qty }; default: return state; } }; export const useCountStore createState((set) ({ count: 0, dispatch: (action: Action) set((state) countReducer(state, action)), }));6.2 Jotai配置安装pnpm add jotai创建状态存储src/store/index.tsimport { atom } from jotai; export const animeAtom atom([ { title: Ghost in the Shell, year: 1995, watched: true }, { title: Serial Experiments Lain, year: 1998, watched: false }, ]); export const progressAtom atom((get) { const anime get(animeAtom); return anime.filter((item) item.watched).length / anime.length; });7. 环境变量配置在实际开发中我们通常需要区分开发、测试和生产环境。7.1 创建配置文件在项目根目录创建环境变量配置文件.env所有环境共用VITE_APP_ENVproduction.env.dev开发环境VITE_APP_ENVdevelopment VITE_APP_API_URL/api.env.test测试环境VITE_APP_ENVtest VITE_APP_API_URLhttps://test-api.example.com.env.prod生产环境VITE_APP_ENVproduction VITE_APP_API_URLhttps://api.example.com7.2 使用环境变量在代码中const baseUrl import.meta.env.VITE_APP_API_URL;在vite.config.ts中import { defineConfig, loadEnv } from vite; export default ({ mode }) { const env loadEnv(mode, process.cwd()); console.log(当前环境变量, env.VITE_APP_ENV); return defineConfig({ // 配置内容 }); };7.3 修改package.json脚本{ scripts: { dev: vite --host --mode dev, build: vite build, build:dev: vite build --mode dev, build:test: vite build --mode test, build-preview:dev: pnpm build:dev vite preview --mode dev, build-preview:test: pnpm build:test vite preview --mode test, build-preview: pnpm build vite preview } }8. 配置Husky和Lint-staged8.1 什么是Husky和Lint-stagedHusky是一个简化Git钩子设置的工具允许开发者在各种Git事件触发时运行脚本。Lint-staged是一个在提交代码前运行linter或其他工具的工具确保只有符合规范的代码被提交。8.2 配置Husky安装pnpm add -D husky初始化npx husky init修改.husky/pre-commit文件#!/usr/bin/env sh . $(dirname -- $0)/_/husky.sh npx lint-staged8.3 配置Lint-staged安装pnpm add -D lint-staged修改package.json{ scripts: { lint: eslint . --fix, format: prettier --write src/, prepare: husky }, lint-staged: { *.{js,ts,jsx,tsx,vue}: [ pnpm lint, pnpm format ], *.{scss,css,html,json,md}: [ pnpm format ] } }9. 实用插件推荐9.1 vitejs/plugin-legacy为旧版浏览器提供兼容支持。安装pnpm add -D vitejs/plugin-legacy配置import legacy from vitejs/plugin-legacy; export default defineConfig({ plugins: [ legacy({ targets: [defaults, not IE 11], modernPolyfills: true, renderLegacyChunks: false, }), ], });9.2 vite-plugin-image-optimizer优化图片资源。安装pnpm add -D vite-plugin-image-optimizer sharp svgo配置import { ViteImageOptimizer } from vite-plugin-image-optimizer; export default defineConfig({ plugins: [ViteImageOptimizer()], });9.3 vite-plugin-svgr将SVG转换为React组件。安装pnpm add -D vite-plugin-svgr配置import svgr from vite-plugin-svgr; export default defineConfig({ plugins: [svgr()], });使用import { ReactComponent as Logo } from ./logo.svg; function App() { return Logo width100 fillblue /; }在实际项目中这套配置已经帮助我们团队提高了开发效率减少了代码风格不一致的问题。特别是在大型项目中类型检查和自动化格式化的结合让代码质量得到了显著提升。

更多文章