[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6JDP1WAVYAR5KEWWDKR4Q6P":3,"skill-same:01M6JDP1WAVYAR5KEWWDKR4Q6P":66},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":38,"linkOnly":39,"markdownContent":40,"markdownBody":41,"frontMatter":42,"refName":44,"commitSha":45,"skillDirectory":46,"forksCount":47,"repositoryHtmlUrl":48,"repositoryHomepageUrl":49,"ownerHtmlUrl":50,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":51,"install":52,"resources":65},"01M6JDP1WAVYAR5KEWWDKR4Q6P","vite-patterns",null,"Vite build tool patterns including config, plugins, HMR, env variables, proxy setup, SSR, library mode, dependency pre-bundling, and build optimization. Activate when working with vite.config.ts, Vite plugins, or Vite-based projects.","S3YED\u002Fappie-kit","S3YED","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F62743867?v=4","01M6JBKBRRVP6KMS0VWZ27T3R6","01M6JBKBX0KG30284PW1DBYJT1",14,"MIT","https:\u002F\u002Fgithub.com\u002FS3YED\u002Fappie-kit\u002Fblob\u002Fmaster\u002Fskills\u002Fecc\u002Fvite-patterns\u002FSKILL.md",[],[18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37],"vite","vite patterns","patterns","dependency","setup","mode","Variables","with","env","ssr","activate","build","proxy","config","tool","projects","build tool","Optimization","library","plugins","2026-11-10 10:12:30",false,"---\nname: vite-patterns\ndescription: Vite build tool patterns including config, plugins, HMR, env variables, proxy setup, SSR, library mode, dependency pre-bundling, and build optimization. Activate when working with vite.config.ts, Vite plugins, or Vite-based projects.\norigin: ECC\n---\n\n# Vite Patterns\n\nBuild tool and dev server patterns for Vite 8+ projects. Covers configuration, environment variables, proxy setup, library mode, dependency pre-bundling, and common production pitfalls.\n\n## When to Use\n\n- Configuring `vite.config.ts` or `vite.config.js`\n- Setting up environment variables or `.env` files\n- Configuring dev server proxy for API backends\n- Optimizing build output (chunks, minification, assets)\n- Publishing libraries with `build.lib`\n- Troubleshooting dependency pre-bundling or CJS\u002FESM interop\n- Debugging HMR, dev server, or build errors\n- Choosing or ordering Vite plugins\n\n## How It Works\n\n- **Dev mode** serves source files as native ESM — no bundling. Transforms happen on-demand per module request, which is why cold starts are fast and HMR is precise.\n- **Build mode** uses Rolldown (v7+) or Rollup (v5–v6) to bundle the app for production with tree-shaking, code-splitting, and Oxc-based minification.\n- **Dependency pre-bundling** converts CJS\u002FUMD deps to ESM once via esbuild and caches the result under `node_modules\u002F.vite`, so subsequent starts skip the work.\n- **Plugins** share a unified interface across dev and build — the same plugin object works for both the dev server's on-demand transforms and the production pipeline.\n- **Environment variables** are statically inlined at build time. `VITE_`-prefixed vars become public constants in the bundle; everything unprefixed is invisible to client code.\n\n## Examples\n\n### Config Structure\n\n#### Basic Config\n\n```typescript\n\u002F\u002F vite.config.ts\nimport { defineConfig } from 'vite'\nimport react from '@vitejs\u002Fplugin-react'\n\nexport default defineConfig({\n  plugins: [react()],\n  resolve: {\n    alias: { '@': new URL('.\u002Fsrc', import.meta.url).pathname },\n  },\n})\n```\n\n#### Conditional Config\n\n```typescript\n\u002F\u002F vite.config.ts\nimport { defineConfig, loadEnv } from 'vite'\nimport react from '@vitejs\u002Fplugin-react'\n\nexport default defineConfig(({ command, mode }) => {\n  const env = loadEnv(mode, process.cwd())   \u002F\u002F VITE_ prefixed only (safe)\n\n  return {\n    plugins: [react()],\n    server: command === 'serve' ? { port: 3000 } : undefined,\n    define: {\n      __API_URL__: JSON.stringify(env.VITE_API_URL),\n    },\n  }\n})\n```\n\n#### Key Config Options\n\n| Key | Default | Description |\n|-----|---------|-------------|\n| `root` | `'.'` | Project root (where `index.html` lives) |\n| `base` | `'\u002F'` | Public base path for deployed assets |\n| `envPrefix` | `'VITE_'` | Prefix for client-exposed env vars |\n| `build.outDir` | `'dist'` | Output directory |\n| `build.minify` | `'oxc'` | Minifier (`'oxc'`, `'terser'`, or `false`) |\n| `build.sourcemap` | `false` | `true`, `'inline'`, or `'hidden'` |\n\n### Plugins\n\n#### Essential Plugins\n\nMost plugin needs are covered by a handful of well-maintained packages. Reach for these before writing your own.\n\n| Plugin | Purpose | When to use |\n|--------|---------|-------------|\n| `@vitejs\u002Fplugin-react-swc` | React HMR + Fast Refresh via SWC | Default for React apps (faster than Babel variant) |\n| `@vitejs\u002Fplugin-react` | React HMR + Fast Refresh via Babel | Only if you need Babel plugins (emotion, MobX decorators) |\n| `@vitejs\u002Fplugin-vue` | Vue 3 SFC support | Vue apps |\n| `vite-plugin-checker` | Runs `tsc` + ESLint in worker thread with HMR overlay | **Any TypeScript app** — Vite does NOT type-check during `vite build` |\n| `vite-tsconfig-paths` | Honors `tsconfig.json` `paths` aliases | Any time you already have aliases in `tsconfig.json` |\n| `vite-plugin-dts` | Emits `.d.ts` files in library mode | Publishing TypeScript libraries |\n| `vite-plugin-svgr` | Imports SVGs as React components | React apps using SVGs as components |\n| `rollup-plugin-visualizer` | Bundle treemap\u002Fsunburst report | Periodic bundle size audits (use `enforce: 'post'`) |\n| `vite-plugin-pwa` | Zero-config PWA + Workbox | Offline-capable apps |\n\n**Critical callout:** `vite build` transpiles but does NOT type-check. Type errors silently ship to production unless you add `vite-plugin-checker` or run `tsc --noEmit` in CI.\n\n#### Authoring Custom Plugins\n\nAuthoring is rare — most needs are covered by existing plugins. When you do need one, start inline in `vite.config.ts` and only extract if reused.\n\n```typescript\n\u002F\u002F vite.config.ts — minimal inline plugin\nfunction myPlugin(): Plugin {\n  return {\n    name: 'my-plugin',                       \u002F\u002F required, must be unique\n    enforce: 'pre',                           \u002F\u002F 'pre' | 'post' (optional)\n    apply: 'build',                           \u002F\u002F 'build' | 'serve' (optional)\n    transform(code, id) {\n      if (!id.endsWith('.custom')) return\n      return { code: transformCustom(code), map: null }\n    },\n  }\n}\n```\n\n**Key hooks:** `transform` (modify source), `resolveId` + `load` (virtual modules), `transformIndexHtml` (inject into HTML), `configureServer` (add dev middleware), `hotUpdate` (custom HMR — replaces deprecated `handleHotUpdate` in v7+).\n\n**Virtual modules** use the `\\0` prefix convention — `resolveId` returns `'\\0virtual:my-id'` so other plugins skip it. User code imports `'virtual:my-id'`.\n\nFor full plugin API, see [vite.dev\u002Fguide\u002Fapi-plugin](https:\u002F\u002Fvite.dev\u002Fguide\u002Fapi-plugin). Use `vite-plugin-inspect` during development to debug the transform pipeline.\n\n### HMR API\n\nFramework plugins (`@vitejs\u002Fplugin-react`, `@vitejs\u002Fplugin-vue`, etc.) handle HMR automatically. Reach for `import.meta.hot` directly only when building custom state stores, dev tools, or framework-agnostic utilities that need to persist state across updates.\n\n```typescript\n\u002F\u002F src\u002Fstore.ts — manual HMR for a vanilla module\nif (import.meta.hot) {\n  \u002F\u002F Persist state across updates (must MUTATE, never reassign .data)\n  import.meta.hot.data.count = import.meta.hot.data.count ?? 0\n\n  \u002F\u002F Cleanup side effects before module is replaced\n  import.meta.hot.dispose((data) => clearInterval(data.intervalId))\n\n  \u002F\u002F Accept this module's own updates\n  import.meta.hot.accept()\n}\n```\n\nAll `import.meta.hot` code is tree-shaken out of production builds — no guard removal needed.\n\n### Environment Variables\n\nVite loads `.env`, `.env.local`, `.env.[mode]`, and `.env.[mode].local` in that order (later overrides earlier); `*.local` files are gitignored and meant for local secrets.\n\n#### Client-Side Access\n\nOnly `VITE_`-prefixed vars are exposed to client code:\n\n```typescript\nimport.meta.env.VITE_API_URL   \u002F\u002F string\nimport.meta.env.MODE            \u002F\u002F 'development' | 'production' | custom\nimport.meta.env.BASE_URL        \u002F\u002F base config value\nimport.meta.env.DEV             \u002F\u002F boolean\nimport.meta.env.PROD            \u002F\u002F boolean\nimport.meta.env.SSR             \u002F\u002F boolean\n```\n\n#### Using Env in Config\n\n```typescript\n\u002F\u002F vite.config.ts\nimport { defineConfig, loadEnv } from 'vite'\n\nexport default defineConfig(({ mode }) => {\n  const env = loadEnv(mode, process.cwd())          \u002F\u002F VITE_ prefixed only (safe)\n  return {\n    define: {\n      __API_URL__: JSON.stringify(env.VITE_API_URL),\n    },\n  }\n})\n```\n\n### Security\n\n#### `VITE_` Prefix is NOT a Security Boundary\n\nAny variable prefixed with `VITE_` is **statically inlined into the client bundle at build time**. Minification, base64 encoding, and disabling source maps do NOT hide it. A determined attacker can extract any `VITE_` var from the shipped JavaScript.\n\n**Rule:** Only public values (API URLs, feature flags, public keys) go in `VITE_` vars. Secrets (API tokens, database URLs, private keys) MUST live server-side behind an API or serverless function.\n\n#### The `loadEnv('')` Trap\n\n```typescript\n\u002F\u002F BAD: passing '' as the third arg loads ALL env vars — including server secrets —\n\u002F\u002F and makes them available to inline into client code via `define`.\nconst env = loadEnv(mode, process.cwd(), '')\n\n\u002F\u002F GOOD: explicit prefix list\nconst env = loadEnv(mode, process.cwd(), ['VITE_', 'APP_'])\n```\n\n#### Source Maps in Production\n\nProduction source maps leak your original source code. Disable them unless you upload to an error tracker (Sentry, Bugsnag) and delete locally afterward:\n\n```typescript\nbuild: {\n  sourcemap: false,                                  \u002F\u002F default — keep it this way\n}\n```\n\n#### `.gitignore` Checklist\n\n- `.env.local`, `.env.*.local` — local secret overrides\n- `dist\u002F` — build output\n- `node_modules\u002F.vite` — pre-bundle cache (stale entries cause phantom errors)\n\n### Server Proxy\n\n```typescript\n\u002F\u002F vite.config.ts — server.proxy\nserver: {\n  proxy: {\n    '\u002Ffoo': 'http:\u002F\u002Flocalhost:4567',                    \u002F\u002F string shorthand\n\n    '\u002Fapi': {\n      target: 'http:\u002F\u002Flocalhost:8080',\n      changeOrigin: true,                               \u002F\u002F needed for virtual-hosted backends\n      rewrite: (path) => path.replace(\u002F^\\\u002Fapi\u002F, ''),\n    },\n  },\n}\n```\n\nFor WebSocket proxying, add `ws: true` to the route config.\n\n### Build Optimization\n\n#### Manual Chunks\n\n```typescript\n\u002F\u002F vite.config.ts — build.rolldownOptions\nbuild: {\n  rolldownOptions: {\n    output: {\n      \u002F\u002F Object form: group specific packages\n      manualChunks: {\n        'react-vendor': ['react', 'react-dom'],\n        'ui-vendor': ['@radix-ui\u002Freact-dialog', '@radix-ui\u002Freact-popover'],\n      },\n    },\n  },\n}\n```\n\n```typescript\n\u002F\u002F Function form: split by heuristic\nmanualChunks(id) {\n  if (id.includes('node_modules\u002Freact')) return 'react-vendor'\n  if (id.includes('node_modules')) return 'vendor'\n}\n```\n\n### Performance\n\n#### Avoid Barrel Files\n\nBarrel files (`index.ts` re-exporting everything from a directory) force Vite to load every re-exported file even when you import a single symbol. This is the #1 dev-server slowdown flagged by the official docs.\n\n```typescript\n\u002F\u002F BAD — importing one util forces Vite to load the whole barrel\nimport { slash } from '@\u002Futils'\n\n\u002F\u002F GOOD — direct import, only the one file is loaded\nimport { slash } from '@\u002Futils\u002Fslash'\n```\n\n#### Be Explicit with Import Extensions\n\nEach implicit extension forces up to 6 filesystem checks via `resolve.extensions`. In large codebases, this adds up.\n\n```typescript\n\u002F\u002F BAD\nimport Component from '.\u002FComponent'\n\n\u002F\u002F GOOD\nimport Component from '.\u002FComponent.tsx'\n```\n\nNarrow `tsconfig.json` `allowImportingTsExtensions` + `resolve.extensions` to only the extensions you actually use.\n\n#### Warm-Up Hot-Path Routes\n\n`server.warmup.clientFiles` pre-transforms known hot entries before the browser requests them — eliminating the cold-load request waterfall on large apps.\n\n```typescript\n\u002F\u002F vite.config.ts\nserver: {\n  warmup: {\n    clientFiles: ['.\u002Fsrc\u002Fmain.tsx', '.\u002Fsrc\u002Froutes\u002F**\u002F*.tsx'],\n  },\n}\n```\n\n#### Profiling Slow Dev Servers\n\nWhen `vite dev` feels slow, start with `vite --profile`, interact with the app, then press `p+enter` to save a `.cpuprofile`. Load it in [Speedscope](https:\u002F\u002Fwww.speedscope.app) to find which plugins are eating time — usually `buildStart`, `config`, or `configResolved` hooks in community plugins.\n\n### Library Mode\n\nWhen publishing an npm package, use `build.lib`. Two footguns matter more than config detail:\n\n1. **Types are not emitted** — add `vite-plugin-dts` or run `tsc --emitDeclarationOnly` separately.\n2. **Peer dependencies MUST be externalized** — unlisted peers get bundled into your library, causing duplicate-runtime errors in consumers.\n\n```typescript\n\u002F\u002F vite.config.ts\nbuild: {\n  lib: {\n    entry: 'src\u002Findex.ts',\n    formats: ['es', 'cjs'],\n    fileName: (format) => `my-lib.${format}.js`,\n  },\n  rolldownOptions: {\n    external: ['react', 'react-dom', 'react\u002Fjsx-runtime'],  \u002F\u002F every peer dep\n  },\n}\n```\n\n### SSR Externals\n\nBare `createServer({ middlewareMode: true })` setups are framework-author territory. Most apps should use Nuxt, Remix, SvelteKit, Astro, or TanStack Start instead. What you *will* tweak as a framework user is the externals config when deps break in SSR:\n\n```typescript\n\u002F\u002F vite.config.ts — ssr options\nssr: {\n  external: ['node-native-package'],           \u002F\u002F keep as require() in SSR bundle\n  noExternal: ['esm-only-package'],            \u002F\u002F force-bundle into SSR output (fixes most SSR errors)\n  target: 'node',                              \u002F\u002F 'node' or 'webworker'\n}\n```\n\n### Dependency Pre-Bundling\n\nVite pre-bundles dependencies to convert CJS\u002FUMD to ESM and reduce request count.\n\n```typescript\n\u002F\u002F vite.config.ts — optimizeDeps\noptimizeDeps: {\n  include: [\n    'lodash-es',                              \u002F\u002F force pre-bundle known heavy deps\n    'cjs-package',                            \u002F\u002F CJS deps that cause interop issues\n    'deep-lib\u002Fcomponents\u002F**',                 \u002F\u002F glob for deep imports\n  ],\n  exclude: ['local-esm-package'],             \u002F\u002F must be valid ESM if excluded\n  force: true,                                \u002F\u002F ignore cache, re-optimize (temporary debugging)\n}\n```\n\n### Common Pitfalls\n\n#### Dev Does Not Match Build\n\nDev uses esbuild\u002FRolldown for transforms; build uses Rolldown for bundling. CJS libraries can behave differently between the two. Always verify with `vite build && vite preview` before deploying.\n\n#### Stale Chunks After Deployment\n\nNew builds produce new chunk hashes. Users with active sessions request old filenames that no longer exist. Vite has no built-in solution. Mitigations:\n\n- Keep old `dist\u002Fassets\u002F` files live for a deployment window\n- Catch dynamic import errors in your router and force a page reload\n\n#### Docker and Containers\n\nVite binds to `localhost` by default, which is unreachable from outside a container:\n\n```typescript\n\u002F\u002F vite.config.ts — Docker\u002Fcontainer setup\nserver: {\n  host: true,                                  \u002F\u002F bind 0.0.0.0\n  hmr: { clientPort: 3000 },                   \u002F\u002F if behind a reverse proxy\n}\n```\n\n#### Monorepo File Access\n\nVite restricts file serving to the project root. Packages outside root are blocked:\n\n```typescript\n\u002F\u002F vite.config.ts — monorepo file access\nserver: {\n  fs: {\n    allow: ['..'],                             \u002F\u002F allow parent directory (workspace root)\n  },\n}\n```\n\n### Anti-Patterns\n\n```typescript\n\u002F\u002F BAD: Setting envPrefix to '' exposes ALL env vars (including secrets) to the client\nenvPrefix: ''\n\n\u002F\u002F BAD: Assuming require() works in application source code — Vite is ESM-first\nconst lib = require('some-lib')                \u002F\u002F use import instead\n\n\u002F\u002F BAD: Splitting every node_module into its own chunk — creates hundreds of tiny files\nmanualChunks(id) {\n  if (id.includes('node_modules')) {\n    return id.split('node_modules\u002F')[1].split('\u002F')[0]   \u002F\u002F one chunk per package\n  }\n}\n\n\u002F\u002F BAD: Not externalizing peer deps in library mode — causes duplicate runtime errors\n\u002F\u002F build.lib without rolldownOptions.external\n\n\u002F\u002F BAD: Using deprecated esbuild minifier\nbuild: { minify: 'esbuild' }                  \u002F\u002F use 'oxc' (default) or 'terser'\n\n\u002F\u002F BAD: Mutating import.meta.hot.data by reassignment\nimport.meta.hot.data = { count: 0 }           \u002F\u002F WRONG: must mutate properties, not reassign\nimport.meta.hot.data.count = 0                 \u002F\u002F CORRECT\n```\n\n**Process anti-patterns:**\n\n- **`vite preview` is NOT a production server** — it is a smoke test for the built bundle. Deploy `dist\u002F` to a real static host (NGINX, Cloudflare Pages, Vercel static) or use a multi-stage Dockerfile.\n- **Expecting `vite build` to type-check** — it only transpiles. Type errors silently ship to production. Add `vite-plugin-checker` or run `tsc --noEmit` in CI.\n- **Shipping `@vitejs\u002Fplugin-legacy` by default** — it bloats bundles ~40%, breaks source-map bundle analyzers, and is unnecessary for the 95%+ of users on modern browsers. Gate it on real analytics, not assumption.\n- **Hand-rolling 30+ `resolve.alias` entries that duplicate `tsconfig.json` paths** — use `vite-tsconfig-paths` instead. Observed in Excalidraw and PostHog; avoid in new projects.\n- **Leaving stale `node_modules\u002F.vite` after dep changes** — pre-bundle cache causes phantom errors. Clear it when switching branches or after patching deps.\n\n## Quick Reference\n\n| Pattern | When to Use |\n|---------|-------------|\n| `defineConfig` | Always — provides type inference |\n| `loadEnv(mode, root, ['VITE_'])` | Access env vars in config (explicit prefix) |\n| `vite-plugin-checker` | Any TypeScript app (fills the type-check gap) |\n| `vite-tsconfig-paths` | Instead of hand-rolled `resolve.alias` |\n| `optimizeDeps.include` | CJS deps causing interop issues |\n| `server.proxy` | Route API requests to backend in dev |\n| `server.host: true` | Docker, containers, remote access |\n| `server.warmup.clientFiles` | Pre-transform hot-path routes |\n| `build.lib` + `external` | Publishing npm packages |\n| `manualChunks` (object) | Vendor bundle splitting |\n| `vite --profile` | Debug slow dev server |\n| `vite build && vite preview` | Smoke-test prod bundle locally (NOT a prod server) |\n\n## Related Skills\n\n- `frontend-patterns` — React component patterns\n- `docker-patterns` — containerized dev with Vite\n- `nextjs-turbopack` — alternative bundler for Next.js\n","# Vite Patterns\n\nBuild tool and dev server patterns for Vite 8+ projects. Covers configuration, environment variables, proxy setup, library mode, dependency pre-bundling, and common production pitfalls.\n\n## When to Use\n\n- Configuring `vite.config.ts` or `vite.config.js`\n- Setting up environment variables or `.env` files\n- Configuring dev server proxy for API backends\n- Optimizing build output (chunks, minification, assets)\n- Publishing libraries with `build.lib`\n- Troubleshooting dependency pre-bundling or CJS\u002FESM interop\n- Debugging HMR, dev server, or build errors\n- Choosing or ordering Vite plugins\n\n## How It Works\n\n- **Dev mode** serves source files as native ESM — no bundling. Transforms happen on-demand per module request, which is why cold starts are fast and HMR is precise.\n- **Build mode** uses Rolldown (v7+) or Rollup (v5–v6) to bundle the app for production with tree-shaking, code-splitting, and Oxc-based minification.\n- **Dependency pre-bundling** converts CJS\u002FUMD deps to ESM once via esbuild and caches the result under `node_modules\u002F.vite`, so subsequent starts skip the work.\n- **Plugins** share a unified interface across dev and build — the same plugin object works for both the dev server's on-demand transforms and the production pipeline.\n- **Environment variables** are statically inlined at build time. `VITE_`-prefixed vars become public constants in the bundle; everything unprefixed is invisible to client code.\n\n## Examples\n\n### Config Structure\n\n#### Basic Config\n\n```typescript\n\u002F\u002F vite.config.ts\nimport { defineConfig } from 'vite'\nimport react from '@vitejs\u002Fplugin-react'\n\nexport default defineConfig({\n  plugins: [react()],\n  resolve: {\n    alias: { '@': new URL('.\u002Fsrc', import.meta.url).pathname },\n  },\n})\n```\n\n#### Conditional Config\n\n```typescript\n\u002F\u002F vite.config.ts\nimport { defineConfig, loadEnv } from 'vite'\nimport react from '@vitejs\u002Fplugin-react'\n\nexport default defineConfig(({ command, mode }) => {\n  const env = loadEnv(mode, process.cwd())   \u002F\u002F VITE_ prefixed only (safe)\n\n  return {\n    plugins: [react()],\n    server: command === 'serve' ? { port: 3000 } : undefined,\n    define: {\n      __API_URL__: JSON.stringify(env.VITE_API_URL),\n    },\n  }\n})\n```\n\n#### Key Config Options\n\n| Key | Default | Description |\n|-----|---------|-------------|\n| `root` | `'.'` | Project root (where `index.html` lives) |\n| `base` | `'\u002F'` | Public base path for deployed assets |\n| `envPrefix` | `'VITE_'` | Prefix for client-exposed env vars |\n| `build.outDir` | `'dist'` | Output directory |\n| `build.minify` | `'oxc'` | Minifier (`'oxc'`, `'terser'`, or `false`) |\n| `build.sourcemap` | `false` | `true`, `'inline'`, or `'hidden'` |\n\n### Plugins\n\n#### Essential Plugins\n\nMost plugin needs are covered by a handful of well-maintained packages. Reach for these before writing your own.\n\n| Plugin | Purpose | When to use |\n|--------|---------|-------------|\n| `@vitejs\u002Fplugin-react-swc` | React HMR + Fast Refresh via SWC | Default for React apps (faster than Babel variant) |\n| `@vitejs\u002Fplugin-react` | React HMR + Fast Refresh via Babel | Only if you need Babel plugins (emotion, MobX decorators) |\n| `@vitejs\u002Fplugin-vue` | Vue 3 SFC support | Vue apps |\n| `vite-plugin-checker` | Runs `tsc` + ESLint in worker thread with HMR overlay | **Any TypeScript app** — Vite does NOT type-check during `vite build` |\n| `vite-tsconfig-paths` | Honors `tsconfig.json` `paths` aliases | Any time you already have aliases in `tsconfig.json` |\n| `vite-plugin-dts` | Emits `.d.ts` files in library mode | Publishing TypeScript libraries |\n| `vite-plugin-svgr` | Imports SVGs as React components | React apps using SVGs as components |\n| `rollup-plugin-visualizer` | Bundle treemap\u002Fsunburst report | Periodic bundle size audits (use `enforce: 'post'`) |\n| `vite-plugin-pwa` | Zero-config PWA + Workbox | Offline-capable apps |\n\n**Critical callout:** `vite build` transpiles but does NOT type-check. Type errors silently ship to production unless you add `vite-plugin-checker` or run `tsc --noEmit` in CI.\n\n#### Authoring Custom Plugins\n\nAuthoring is rare — most needs are covered by existing plugins. When you do need one, start inline in `vite.config.ts` and only extract if reused.\n\n```typescript\n\u002F\u002F vite.config.ts — minimal inline plugin\nfunction myPlugin(): Plugin {\n  return {\n    name: 'my-plugin',                       \u002F\u002F required, must be unique\n    enforce: 'pre',                           \u002F\u002F 'pre' | 'post' (optional)\n    apply: 'build',                           \u002F\u002F 'build' | 'serve' (optional)\n    transform(code, id) {\n      if (!id.endsWith('.custom')) return\n      return { code: transformCustom(code), map: null }\n    },\n  }\n}\n```\n\n**Key hooks:** `transform` (modify source), `resolveId` + `load` (virtual modules), `transformIndexHtml` (inject into HTML), `configureServer` (add dev middleware), `hotUpdate` (custom HMR — replaces deprecated `handleHotUpdate` in v7+).\n\n**Virtual modules** use the `\\0` prefix convention — `resolveId` returns `'\\0virtual:my-id'` so other plugins skip it. User code imports `'virtual:my-id'`.\n\nFor full plugin API, see [vite.dev\u002Fguide\u002Fapi-plugin](https:\u002F\u002Fvite.dev\u002Fguide\u002Fapi-plugin). Use `vite-plugin-inspect` during development to debug the transform pipeline.\n\n### HMR API\n\nFramework plugins (`@vitejs\u002Fplugin-react`, `@vitejs\u002Fplugin-vue`, etc.) handle HMR automatically. Reach for `import.meta.hot` directly only when building custom state stores, dev tools, or framework-agnostic utilities that need to persist state across updates.\n\n```typescript\n\u002F\u002F src\u002Fstore.ts — manual HMR for a vanilla module\nif (import.meta.hot) {\n  \u002F\u002F Persist state across updates (must MUTATE, never reassign .data)\n  import.meta.hot.data.count = import.meta.hot.data.count ?? 0\n\n  \u002F\u002F Cleanup side effects before module is replaced\n  import.meta.hot.dispose((data) => clearInterval(data.intervalId))\n\n  \u002F\u002F Accept this module's own updates\n  import.meta.hot.accept()\n}\n```\n\nAll `import.meta.hot` code is tree-shaken out of production builds — no guard removal needed.\n\n### Environment Variables\n\nVite loads `.env`, `.env.local`, `.env.[mode]`, and `.env.[mode].local` in that order (later overrides earlier); `*.local` files are gitignored and meant for local secrets.\n\n#### Client-Side Access\n\nOnly `VITE_`-prefixed vars are exposed to client code:\n\n```typescript\nimport.meta.env.VITE_API_URL   \u002F\u002F string\nimport.meta.env.MODE            \u002F\u002F 'development' | 'production' | custom\nimport.meta.env.BASE_URL        \u002F\u002F base config value\nimport.meta.env.DEV             \u002F\u002F boolean\nimport.meta.env.PROD            \u002F\u002F boolean\nimport.meta.env.SSR             \u002F\u002F boolean\n```\n\n#### Using Env in Config\n\n```typescript\n\u002F\u002F vite.config.ts\nimport { defineConfig, loadEnv } from 'vite'\n\nexport default defineConfig(({ mode }) => {\n  const env = loadEnv(mode, process.cwd())          \u002F\u002F VITE_ prefixed only (safe)\n  return {\n    define: {\n      __API_URL__: JSON.stringify(env.VITE_API_URL),\n    },\n  }\n})\n```\n\n### Security\n\n#### `VITE_` Prefix is NOT a Security Boundary\n\nAny variable prefixed with `VITE_` is **statically inlined into the client bundle at build time**. Minification, base64 encoding, and disabling source maps do NOT hide it. A determined attacker can extract any `VITE_` var from the shipped JavaScript.\n\n**Rule:** Only public values (API URLs, feature flags, public keys) go in `VITE_` vars. Secrets (API tokens, database URLs, private keys) MUST live server-side behind an API or serverless function.\n\n#### The `loadEnv('')` Trap\n\n```typescript\n\u002F\u002F BAD: passing '' as the third arg loads ALL env vars — including server secrets —\n\u002F\u002F and makes them available to inline into client code via `define`.\nconst env = loadEnv(mode, process.cwd(), '')\n\n\u002F\u002F GOOD: explicit prefix list\nconst env = loadEnv(mode, process.cwd(), ['VITE_', 'APP_'])\n```\n\n#### Source Maps in Production\n\nProduction source maps leak your original source code. Disable them unless you upload to an error tracker (Sentry, Bugsnag) and delete locally afterward:\n\n```typescript\nbuild: {\n  sourcemap: false,                                  \u002F\u002F default — keep it this way\n}\n```\n\n#### `.gitignore` Checklist\n\n- `.env.local`, `.env.*.local` — local secret overrides\n- `dist\u002F` — build output\n- `node_modules\u002F.vite` — pre-bundle cache (stale entries cause phantom errors)\n\n### Server Proxy\n\n```typescript\n\u002F\u002F vite.config.ts — server.proxy\nserver: {\n  proxy: {\n    '\u002Ffoo': 'http:\u002F\u002Flocalhost:4567',                    \u002F\u002F string shorthand\n\n    '\u002Fapi': {\n      target: 'http:\u002F\u002Flocalhost:8080',\n      changeOrigin: true,                               \u002F\u002F needed for virtual-hosted backends\n      rewrite: (path) => path.replace(\u002F^\\\u002Fapi\u002F, ''),\n    },\n  },\n}\n```\n\nFor WebSocket proxying, add `ws: true` to the route config.\n\n### Build Optimization\n\n#### Manual Chunks\n\n```typescript\n\u002F\u002F vite.config.ts — build.rolldownOptions\nbuild: {\n  rolldownOptions: {\n    output: {\n      \u002F\u002F Object form: group specific packages\n      manualChunks: {\n        'react-vendor': ['react', 'react-dom'],\n        'ui-vendor': ['@radix-ui\u002Freact-dialog', '@radix-ui\u002Freact-popover'],\n      },\n    },\n  },\n}\n```\n\n```typescript\n\u002F\u002F Function form: split by heuristic\nmanualChunks(id) {\n  if (id.includes('node_modules\u002Freact')) return 'react-vendor'\n  if (id.includes('node_modules')) return 'vendor'\n}\n```\n\n### Performance\n\n#### Avoid Barrel Files\n\nBarrel files (`index.ts` re-exporting everything from a directory) force Vite to load every re-exported file even when you import a single symbol. This is the #1 dev-server slowdown flagged by the official docs.\n\n```typescript\n\u002F\u002F BAD — importing one util forces Vite to load the whole barrel\nimport { slash } from '@\u002Futils'\n\n\u002F\u002F GOOD — direct import, only the one file is loaded\nimport { slash } from '@\u002Futils\u002Fslash'\n```\n\n#### Be Explicit with Import Extensions\n\nEach implicit extension forces up to 6 filesystem checks via `resolve.extensions`. In large codebases, this adds up.\n\n```typescript\n\u002F\u002F BAD\nimport Component from '.\u002FComponent'\n\n\u002F\u002F GOOD\nimport Component from '.\u002FComponent.tsx'\n```\n\nNarrow `tsconfig.json` `allowImportingTsExtensions` + `resolve.extensions` to only the extensions you actually use.\n\n#### Warm-Up Hot-Path Routes\n\n`server.warmup.clientFiles` pre-transforms known hot entries before the browser requests them — eliminating the cold-load request waterfall on large apps.\n\n```typescript\n\u002F\u002F vite.config.ts\nserver: {\n  warmup: {\n    clientFiles: ['.\u002Fsrc\u002Fmain.tsx', '.\u002Fsrc\u002Froutes\u002F**\u002F*.tsx'],\n  },\n}\n```\n\n#### Profiling Slow Dev Servers\n\nWhen `vite dev` feels slow, start with `vite --profile`, interact with the app, then press `p+enter` to save a `.cpuprofile`. Load it in [Speedscope](https:\u002F\u002Fwww.speedscope.app) to find which plugins are eating time — usually `buildStart`, `config`, or `configResolved` hooks in community plugins.\n\n### Library Mode\n\nWhen publishing an npm package, use `build.lib`. Two footguns matter more than config detail:\n\n1. **Types are not emitted** — add `vite-plugin-dts` or run `tsc --emitDeclarationOnly` separately.\n2. **Peer dependencies MUST be externalized** — unlisted peers get bundled into your library, causing duplicate-runtime errors in consumers.\n\n```typescript\n\u002F\u002F vite.config.ts\nbuild: {\n  lib: {\n    entry: 'src\u002Findex.ts',\n    formats: ['es', 'cjs'],\n    fileName: (format) => `my-lib.${format}.js`,\n  },\n  rolldownOptions: {\n    external: ['react', 'react-dom', 'react\u002Fjsx-runtime'],  \u002F\u002F every peer dep\n  },\n}\n```\n\n### SSR Externals\n\nBare `createServer({ middlewareMode: true })` setups are framework-author territory. Most apps should use Nuxt, Remix, SvelteKit, Astro, or TanStack Start instead. What you *will* tweak as a framework user is the externals config when deps break in SSR:\n\n```typescript\n\u002F\u002F vite.config.ts — ssr options\nssr: {\n  external: ['node-native-package'],           \u002F\u002F keep as require() in SSR bundle\n  noExternal: ['esm-only-package'],            \u002F\u002F force-bundle into SSR output (fixes most SSR errors)\n  target: 'node',                              \u002F\u002F 'node' or 'webworker'\n}\n```\n\n### Dependency Pre-Bundling\n\nVite pre-bundles dependencies to convert CJS\u002FUMD to ESM and reduce request count.\n\n```typescript\n\u002F\u002F vite.config.ts — optimizeDeps\noptimizeDeps: {\n  include: [\n    'lodash-es',                              \u002F\u002F force pre-bundle known heavy deps\n    'cjs-package',                            \u002F\u002F CJS deps that cause interop issues\n    'deep-lib\u002Fcomponents\u002F**',                 \u002F\u002F glob for deep imports\n  ],\n  exclude: ['local-esm-package'],             \u002F\u002F must be valid ESM if excluded\n  force: true,                                \u002F\u002F ignore cache, re-optimize (temporary debugging)\n}\n```\n\n### Common Pitfalls\n\n#### Dev Does Not Match Build\n\nDev uses esbuild\u002FRolldown for transforms; build uses Rolldown for bundling. CJS libraries can behave differently between the two. Always verify with `vite build && vite preview` before deploying.\n\n#### Stale Chunks After Deployment\n\nNew builds produce new chunk hashes. Users with active sessions request old filenames that no longer exist. Vite has no built-in solution. Mitigations:\n\n- Keep old `dist\u002Fassets\u002F` files live for a deployment window\n- Catch dynamic import errors in your router and force a page reload\n\n#### Docker and Containers\n\nVite binds to `localhost` by default, which is unreachable from outside a container:\n\n```typescript\n\u002F\u002F vite.config.ts — Docker\u002Fcontainer setup\nserver: {\n  host: true,                                  \u002F\u002F bind 0.0.0.0\n  hmr: { clientPort: 3000 },                   \u002F\u002F if behind a reverse proxy\n}\n```\n\n#### Monorepo File Access\n\nVite restricts file serving to the project root. Packages outside root are blocked:\n\n```typescript\n\u002F\u002F vite.config.ts — monorepo file access\nserver: {\n  fs: {\n    allow: ['..'],                             \u002F\u002F allow parent directory (workspace root)\n  },\n}\n```\n\n### Anti-Patterns\n\n```typescript\n\u002F\u002F BAD: Setting envPrefix to '' exposes ALL env vars (including secrets) to the client\nenvPrefix: ''\n\n\u002F\u002F BAD: Assuming require() works in application source code — Vite is ESM-first\nconst lib = require('some-lib')                \u002F\u002F use import instead\n\n\u002F\u002F BAD: Splitting every node_module into its own chunk — creates hundreds of tiny files\nmanualChunks(id) {\n  if (id.includes('node_modules')) {\n    return id.split('node_modules\u002F')[1].split('\u002F')[0]   \u002F\u002F one chunk per package\n  }\n}\n\n\u002F\u002F BAD: Not externalizing peer deps in library mode — causes duplicate runtime errors\n\u002F\u002F build.lib without rolldownOptions.external\n\n\u002F\u002F BAD: Using deprecated esbuild minifier\nbuild: { minify: 'esbuild' }                  \u002F\u002F use 'oxc' (default) or 'terser'\n\n\u002F\u002F BAD: Mutating import.meta.hot.data by reassignment\nimport.meta.hot.data = { count: 0 }           \u002F\u002F WRONG: must mutate properties, not reassign\nimport.meta.hot.data.count = 0                 \u002F\u002F CORRECT\n```\n\n**Process anti-patterns:**\n\n- **`vite preview` is NOT a production server** — it is a smoke test for the built bundle. Deploy `dist\u002F` to a real static host (NGINX, Cloudflare Pages, Vercel static) or use a multi-stage Dockerfile.\n- **Expecting `vite build` to type-check** — it only transpiles. Type errors silently ship to production. Add `vite-plugin-checker` or run `tsc --noEmit` in CI.\n- **Shipping `@vitejs\u002Fplugin-legacy` by default** — it bloats bundles ~40%, breaks source-map bundle analyzers, and is unnecessary for the 95%+ of users on modern browsers. Gate it on real analytics, not assumption.\n- **Hand-rolling 30+ `resolve.alias` entries that duplicate `tsconfig.json` paths** — use `vite-tsconfig-paths` instead. Observed in Excalidraw and PostHog; avoid in new projects.\n- **Leaving stale `node_modules\u002F.vite` after dep changes** — pre-bundle cache causes phantom errors. Clear it when switching branches or after patching deps.\n\n## Quick Reference\n\n| Pattern | When to Use |\n|---------|-------------|\n| `defineConfig` | Always — provides type inference |\n| `loadEnv(mode, root, ['VITE_'])` | Access env vars in config (explicit prefix) |\n| `vite-plugin-checker` | Any TypeScript app (fills the type-check gap) |\n| `vite-tsconfig-paths` | Instead of hand-rolled `resolve.alias` |\n| `optimizeDeps.include` | CJS deps causing interop issues |\n| `server.proxy` | Route API requests to backend in dev |\n| `server.host: true` | Docker, containers, remote access |\n| `server.warmup.clientFiles` | Pre-transform hot-path routes |\n| `build.lib` + `external` | Publishing npm packages |\n| `manualChunks` (object) | Vendor bundle splitting |\n| `vite --profile` | Debug slow dev server |\n| `vite build && vite preview` | Smoke-test prod bundle locally (NOT a prod server) |\n\n## Related Skills\n\n- `frontend-patterns` — React component patterns\n- `docker-patterns` — containerized dev with Vite\n- `nextjs-turbopack` — alternative bundler for Next.js\n",{"name":5,"origin":43,"description":7},"ECC","master","8ec37df6d71fb664ea19d32c079e7d3ff931a8e0","skills\u002Fecc\u002Fvite-patterns",3,"https:\u002F\u002Fgithub.com\u002FS3YED\u002Fappie-kit","https:\u002F\u002Fweblyfe.ai","https:\u002F\u002Fgithub.com\u002FS3YED","2026-08-27 01:54:02",{"source":8,"skillName":5,"commands":53,"prompt":63,"zipAvailable":64},[54,57,60],{"tool":55,"command":56},"npx","npx skills add S3YED\u002Fappie-kit --skill vite-patterns",{"tool":58,"command":59},"bunx","bunx skills add S3YED\u002Fappie-kit --skill vite-patterns",{"tool":61,"command":62},"pnpm","pnpm dlx skills add S3YED\u002Fappie-kit --skill vite-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FS3YED\u002Fappie-kit\u002Fblob\u002Fmaster\u002Fskills\u002Fecc\u002Fvite-patterns\u002FSKILL.md",true,[],[67,92,119,143,170,194],{"skillNo":68,"name":69,"nameZh":6,"description":70,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":38},"01M6JFD4M6N4DSGC7TXEJ5R3J2","ai-music","AI music generation and audio tools: HeartMuLa lyrics-to-music generation, songwriting craft (+ Suno prompts), and audio spectrogram\u002Ffeature visualization.","https:\u002F\u002Fgithub.com\u002FS3YED\u002Fappie-kit\u002Fblob\u002Fmaster\u002Fskills\u002Fwethlete\u002Fai-music\u002FSKILL.md",[],[74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91],"music","ai music","humanizer","visualization","Tools","Audio","hermes","hermes agent","songwriting","suno","lyrics","prompts","heartmula","craft","generation","feature","ai music generation","music generation",{"skillNo":93,"name":94,"nameZh":6,"description":95,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":38},"01M6JFCZE4XNFQFMNZDHKHT5V5","agentic-webdesign-design-system-ingestion","Use v0 Design Systems 2.0, Bolt Design System Agents, or Lovable to generate production UI from a client's real design system components — not generic Tailwind. Use when building a client website where brand consistency matters.","https:\u002F\u002Fgithub.com\u002FS3YED\u002Fappie-kit\u002Fblob\u002Fmaster\u002Fskills\u002Fweb-design\u002Fagentic-webdesign-design-system-ingestion\u002FSKILL.md",[],[99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118],"design","agentic","design system","system","ingestion","webdesign","agentic webdesign design system ingestion","components","generate","design systems","website","ui","Tailwind","bolt","lovable","v0","design-system","wed","design system components","appie",{"skillNo":120,"name":121,"nameZh":6,"description":122,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":123,"categories":124,"keywords":125,"publishedAt":38},"01M6JFCVPX3913CFAS6QQJ33ZB","agentic-webdesign-agent-elements","Use 21st.dev Agent Elements — 25 shadcn\u002Fui components purpose-built for AI agent UIs. Tool cards (Bash, Edit, Search, Plan, Subagent, MCP), chat, input, streaming. Open source, shadcn-registry install, no runtime lock-in.","https:\u002F\u002Fgithub.com\u002FS3YED\u002Fappie-kit\u002Fblob\u002Fmaster\u002Fskills\u002Fweb-design\u002Fagentic-webdesign-agent-elements\u002FSKILL.md",[],[100,126,104,127,128,129,106,130,131,132,133,134,135,136,137,138,139,140,141,142],"elements","agentic webdesign agent elements","MCP","ai agent","registry","search","streaming","open source","open","Bash","plan","subagent","edit","install","input","lock","source",{"skillNo":144,"name":145,"nameZh":6,"description":146,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":147,"categories":148,"keywords":149,"publishedAt":38},"01M6JFCQC7H65M9QJ6TRE71BS1","vercel-deployment","Deploy static sites and frontends to Vercel — handles both CLI and REST API paths, including the CLI token sanitization workaround.","https:\u002F\u002Fgithub.com\u002FS3YED\u002Fappie-kit\u002Fblob\u002Fmaster\u002Fskills\u002Fsoftware-development\u002Fvercel-deployment\u002FSKILL.md",[],[150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169],"deployment","vercel deployment","vercel","macos","cli","linux","windows","deploy","vercel deploy","REST","api","site","deploy to vercel","token","rest api","host","sites","paths","sanitization","static site",{"skillNo":171,"name":172,"nameZh":6,"description":173,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":174,"categories":175,"keywords":176,"publishedAt":38},"01M6JFCM4SMTXBM5A01BK2YQG1","software-quality-workflows","Umbrella workflow for TDD, debugging, code simplification, spikes, pre-commit review, and debugger-assisted investigation.","https:\u002F\u002Fgithub.com\u002FS3YED\u002Fappie-kit\u002Fblob\u002Fmaster\u002Fskills\u002Fsoftware-development\u002Fsoftware-quality-workflows\u002FSKILL.md",[],[177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193],"workflows","quality","software","software quality workflows","review","tdd","workflow","commit","debugging","code","debugger","pre-commit","investigation","code simplification","user","simplification","for",{"skillNo":195,"name":196,"nameZh":6,"description":197,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":198,"categories":199,"keywords":200,"publishedAt":38},"01M6JFCGD0M6CEATY01W7YN6DB","react-component-refactoring","Safely refactor large React components into smaller, maintainable pieces using proven patterns","https:\u002F\u002Fgithub.com\u002FS3YED\u002Fappie-kit\u002Fblob\u002Fmaster\u002Fskills\u002Fsoftware-development\u002Freact-component-refactoring\u002FSKILL.md",[],[201,202,203,204,205,206,207,208,153,209,210,106,211,156,212,186,213,214,20,215],"react","component","refactoring","component refactoring","react component","react component refactoring","frontend","writing","safe","typescript","react components","modular","refactor","simplify","test-driven-development"]