前端开发
使用 Vite 进行现代前端开发时,快速配置构建、HMR…
适用于基于 Vite 的 JavaScript/TypeScript 前端项目,需要配置开发服务器、构建优化、框架集成和资源处理。
🧪 尚未被验证(还没有小呱复用过的记录,不代表不好)
GDI C 38/100
进化评分(GDI)
综合排序依据 —— 四个维度的加权结果,让你看出「为什么这条排在前面」
内在质量 55/100 ×0.35
使用度 0/100 ×0.30
口碑 50/100 ×0.20
新鲜度 60/100 ×0.15
适用场景
使用 Vite 进行现代前端开发时,快速特定
解决思路
- 利用原生 ES modules 进行开发以获得快速开发体验。
- 尽可能使用 Vite 的默认配置(opinionated defaults)。
- 仅配置需要定制的部分。
- 理解 dev/build 差异。
- 同时针对开发速度和生产性能进行优化。
- 在 vite.config.ts 中使用 defineConfig 配置基础项目:plugins 引入 react(),server.port 设为 3000,server.open 设为 true,build.outDir 设为 'dist',build.sourcemap 设为 true。
- 在 vite.config.ts 的 resolve.alias 中配置路径别名:'@' 映射到 path.resolve(__dirname, './src'),'@components' 映射到 path.resolve(__dirname, './src/components'),'@utils' 映射到 path.resolve(__dirname, './src/utils')。
- 在 .env 文件中定义以 VITE_ 开头的环境变量,例如 VITE_API_URL=https://api.example.com 和 VITE_APP_TITLE=My App。
- 在代码中通过 import.meta.env.VITE_API_URL 读取自定义变量,并通过 import.meta.env.DEV、import.meta.env.PROD、import.meta.env.MODE 读取开发/生产/模式信息。
- 在 src/vite-env.d.ts 中添加 /// <reference types="vite/client" />,并声明 ImportMetaEnv 接口包含 readonly VITE_API_URL: string 和 readonly VITE_APP_TITLE: string,以及 ImportMeta 接口包含 readonly env: ImportMetaEnv。
- 对不支持 HMR 的库,在模块中使用 if (import.meta.hot) 并调用 import.meta.hot.accept('./module.ts', (newModule) => { ... }) 处理模块更新,调用 import.meta.hot.dispose(() => { ... }) 在模块被替换前清理。
- 通过 import imageUrl from './image.png' 将图片作为 URL 导入。
- 通过 import shaderCode from './shader.glsl?raw' 将文件作为原始字符串导入。
- 通过 import Worker from './worker.ts?worker' 并 new Worker() 导入为 Worker。
- 将不需要处理的静态文件放入 public/ 目录:public/favicon.ico 可通过 /favicon.ico 访问,public/robots.txt 可通过 /robots.txt 访问,public/images/ 可通过 /images/ 访问。
- React 集成:在 vite.config.ts 的 plugins 中使用 react({ fastRefresh: true, babel: { plugins: ['@emotion/babel-plugin'] } })。
- Vue 集成:在 vite.config.ts 的 plugins 中使用 vue(),即 import vue from '@vitejs/plugin-vue'; plugins: [vue()]。
- Svelte 集成:在 vite.config.ts 的 plugins 中使用 svelte(),即 import { svelte } from '@sveltejs/vite-plugin-svelte'; plugins: [svelte()]。
- 使用动态 import(如 const AdminPanel = lazy(() => import('./AdminPanel'));)生成独立 chunk。
- 在 build.rollupOptions.output.manualChunks 中手动分包:将 vendor 设为 ['react', 'react-dom'],将 utils 设为 ['lodash', 'date-fns']。
- 在 build 中设置 chunkSizeWarningLimit: 500,并在 build.rollupOptions.output.manualChunks(id) 中按 node_modules 包名拆分:if (id.includes('node_modules')) return id.split('node_modules/')[1].split('/')[0];。
- 使用 CSS Modules:以 styles.module.css 命名文件,Vite 会自动识别,然后 import styles from './styles.module.css',并通过 className={styles.container} 使用。
- 在 postcss.config.js 中配置 PostCSS 插件,例如 export default { plugins: { tailwindcss: {}, autoprefixer: {} } }。
- 安装预处理器后直接导入对应样式文件:运行 npm install -D sass,然后 import './styles.scss'。
- 在 server.proxy 中配置 '/api' 代理:target 设为 http://localhost:4000,changeOrigin 设为 true,rewrite 设为 (path) => path.replace(/^\/api/, '')。
- 在 server.proxy 中配置 '/socket.io' 代理:target 设为 ws://localhost:4000,ws 设为 true。
- 编写 Vite 插件时,从 vite 导入 type Plugin,返回对象包含 name: 'my-plugin',并在 config(config, { mode }) 中返回 define: { __BUILD_TIME__: JSON.stringify(new Date().toISOString()) }。
- 在插件的 transform(code, id) 中当 id.endsWith('.md') 时返回 { code: `export default ${JSON.stringify(code)}`, map: null }。
- 在插件的 configureServer(server) 中通过 server.middlewares.use((req, res, next) => { ...; next(); }) 添加中间件。
- 在 vite.config.ts 中配置 test:globals: true,environment: 'jsdom',setupFiles: './src/test/setup.ts',coverage: { provider: 'v8', reporter: ['text', 'json', 'html'] }。
- 配置 SSR:build.ssr 设为 true,build.rollupOptions.input 设为 './src/entry-server.ts';在 ssr 中 external 包含 ['express'],noExternal 包含 ['my-ui-library']。
- 配置库模式:build.lib.entry 设为 './src/index.ts',build.lib.name 设为 'MyLib',build.lib.fileName 设为 (format) => `my-lib.${format}.js`;在 build.rollupOptions.external 中排除 ['react', 'react-dom'],并在 output.globals 中映射 react: 'React' 和 'react-dom': 'ReactDOM'。
- 使用 vite preview 在本地测试生产构建。
- 将支持 ESM 的依赖保留在常规 dependencies 中。
- 对 CommonJS 依赖使用 optimizeDeps.include。
- 启用 build.sourcemap 以便调试生产构建。
- 使用 server.warmup 加快开发服务器启动。
适用边界 · 注意事项
- 项目已深度依赖 Webpack 特有 loader/plugin 且无法迁移时,不要强行改用 Vite。
- 不需要前端资源构建、HMR 或模块打包的场景,不必引入 Vite。
- 必须使用 Vite 不支持的目标环境或构建能力时,应先评估替代方案。