[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M731GAPNABFSZX4WGDVQ5ERJ":3,"skill-same:01M731GAPNABFSZX4WGDVQ5ERJ":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":25,"commitSha":26,"skillDirectory":27,"forksCount":28,"repositoryHtmlUrl":29,"repositoryHomepageUrl":6,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M731GAPNABFSZX4WGDVQ5ERJ","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.","SriramGandhiS\u002FSkills","SriramGandhiS","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F211849986?v=4","01M72WQCW12BYX71C6WN584TTA","Sriram S","01M72WQCWTJ2RD0ET1X31AF1RC",1,"MIT","https:\u002F\u002Fgithub.com\u002FSriramGandhiS\u002FSkills\u002Fblob\u002Fmaster\u002Fskills\u002Fvite-patterns\u002FSKILL.md",[],[],"2026-11-11 15:11:14",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":24,"description":7},"ECC","master","d6ca01da0f24a3b0e26e4a8b7b66cbd25d429f5d","skills\u002Fvite-patterns",0,"https:\u002F\u002Fgithub.com\u002FSriramGandhiS\u002FSkills","https:\u002F\u002Fgithub.com\u002FSriramGandhiS","https:\u002F\u002Fsriram.website\u002F","Curious guy who keeps tinkering until something works","2026-05-20 16:21:34",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add SriramGandhiS\u002FSkills --skill vite-patterns",{"tool":40,"command":41},"bunx","bunx skills add SriramGandhiS\u002FSkills --skill vite-patterns",{"tool":43,"command":44},"pnpm","pnpm dlx skills add SriramGandhiS\u002FSkills --skill vite-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FSriramGandhiS\u002FSkills\u002Fblob\u002Fmaster\u002Fskills\u002Fvite-patterns\u002FSKILL.md",true,[],[49,56,61,67,74,81],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":19},"01M732609EPJWV13PVTX3GT4TM","webgpu-threejs-tsl","Comprehensive guide for developing WebGPU-enabled Three.js applications using TSL (Three.js Shading Language). Covers WebGPU renderer setup, TSL syntax and node materials, compute shaders, post-processing effects, and WGSL integration. Use this skill when working with Three.js WebGPU, TSL shaders, node materials, or GPU compute in Three.js.","https:\u002F\u002Fgithub.com\u002FSriramGandhiS\u002FSkills\u002Fblob\u002Fmaster\u002Fwebgpu-threejs-tsl\u002Fskills\u002Fwebgpu-threejs-tsl\u002FSKILL.md",[],[],{"skillNo":57,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":58,"categories":59,"keywords":60,"publishedAt":19},"01M7325XM47AGWB6K6C4VXKE6B","https:\u002F\u002Fgithub.com\u002FSriramGandhiS\u002FSkills\u002Fblob\u002Fmaster\u002Fwebgpu-threejs-tsl\u002FSKILL.md",[],[],{"skillNo":62,"name":63,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":64,"categories":65,"keywords":66,"publishedAt":19},"01M7325WP6DES69JKC840VMFEP","verification-loop","https:\u002F\u002Fgithub.com\u002FSriramGandhiS\u002FSkills\u002Fblob\u002Fmaster\u002Fweb-assets\u002Fdocs\u002Fzh-TW\u002Fskills\u002Fverification-loop\u002FSKILL.md",[],[],{"skillNo":68,"name":69,"nameZh":6,"description":70,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":19},"01M7325TFQF1DZTQ6J3WGQQ1VR","tdd-workflow","Use this skill when writing new features, fixing bugs, or refactoring code. Enforces test-driven development with 80%+ coverage including unit, integration, and E2E tests.","https:\u002F\u002Fgithub.com\u002FSriramGandhiS\u002FSkills\u002Fblob\u002Fmaster\u002Fweb-assets\u002Fdocs\u002Fzh-TW\u002Fskills\u002Ftdd-workflow\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":19},"01M7325RGV9AY9PK92D2V8KKPW","strategic-compact","Suggests manual context compaction at logical intervals to preserve context through task phases rather than arbitrary auto-compaction.","https:\u002F\u002Fgithub.com\u002FSriramGandhiS\u002FSkills\u002Fblob\u002Fmaster\u002Fweb-assets\u002Fdocs\u002Fzh-TW\u002Fskills\u002Fstrategic-compact\u002FSKILL.md",[],[],{"skillNo":82,"name":83,"nameZh":6,"description":84,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":85,"categories":86,"keywords":87,"publishedAt":19},"01M7325MZC28SE86E7NMCNEFS4","security-review","Use this skill when adding authentication, handling user input, working with secrets, creating API endpoints, or implementing payment\u002Fsensitive features. Provides comprehensive security checklist and patterns.","https:\u002F\u002Fgithub.com\u002FSriramGandhiS\u002FSkills\u002Fblob\u002Fmaster\u002Fweb-assets\u002Fdocs\u002Fzh-TW\u002Fskills\u002Fsecurity-review\u002FSKILL.md",[],[]]