[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M73880KWJSQNEE57XK3ZVCKX":3,"skill-same:01M73880KWJSQNEE57XK3ZVCKX":49},{"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":30,"ownerHtmlUrl":31,"ownerBlogUrl":32,"ownerDescription":33,"updatedAt":34,"install":35,"resources":48},"01M73880KWJSQNEE57XK3ZVCKX","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.","Horonomos-laps\u002FYana-AI","Horonomos-laps","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F355299122?v=4","01M76B3QPXE88ET2SQPDPVATZT"," Horonomos-laps","01M72ZQRJPCYPSSWT4D00VJR2A",13,"Apache-2.0","https:\u002F\u002Fgithub.com\u002FHoronomos-laps\u002FYana-AI\u002Fblob\u002Fmain\u002F.claude\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","main","481dcd7dd2e288b9d627a2bd017db70e64e6c6fa",".claude\u002Fskills\u002Fvite-patterns",2,"https:\u002F\u002Fgithub.com\u002FHoronomos-laps\u002FYana-AI","https:\u002F\u002Fyana.vutam.link\u002F","https:\u002F\u002Fgithub.com\u002FHoronomos-laps","https:\u002F\u002Fyana.vutam.link","An open-source governed runtime & execution environment for multi-agent AI systems.","2026-11-14 13:24:09",{"source":8,"skillName":5,"commands":36,"prompt":46,"zipAvailable":47},[37,40,43],{"tool":38,"command":39},"npx","npx skills add Horonomos-laps\u002FYana-AI --skill vite-patterns",{"tool":41,"command":42},"bunx","bunx skills add Horonomos-laps\u002FYana-AI --skill vite-patterns",{"tool":44,"command":45},"pnpm","pnpm dlx skills add Horonomos-laps\u002FYana-AI --skill vite-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FHoronomos-laps\u002FYana-AI\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fvite-patterns\u002FSKILL.md",true,[],[50,58,65,73,81,89],{"skillNo":51,"name":52,"nameZh":6,"description":53,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":54,"licenseFileUrl":6,"sourceHtmlUrl":55,"categories":56,"keywords":57,"publishedAt":19},"01M735GKET5YVYKAY62W2P5YXB","openai--sentry--sentry","Use when the user asks to inspect Sentry issues or events, summarize recent production errors, or pull basic Sentry health data via the Sentry API; perform read-only queries with the bundled script and require `SENTRY_AUTH_TOKEN`.","MIT","https:\u002F\u002Fgithub.com\u002FHoronomos-laps\u002FYana-AI\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fopenai--sentry--sentry\u002FSKILL.md",[],[],{"skillNo":59,"name":60,"nameZh":6,"description":61,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":62,"categories":63,"keywords":64,"publishedAt":19},"01M73DCAP83T17HY7SMGK7MGFE","ito-basket-compare","Compare Itô prediction-market baskets against a user's knowledge base, portfolio notes, financial context, watchlist, or research thesis. Use for read-only basket comparison and gap analysis without investment advice or live trading.","https:\u002F\u002Fgithub.com\u002FHoronomos-laps\u002FYana-AI\u002Fblob\u002Fmain\u002Fcore\u002Fskills\u002Fito-basket-compare\u002FSKILL.md",[],[],{"skillNo":66,"name":67,"nameZh":6,"description":68,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":69,"sourceHtmlUrl":70,"categories":71,"keywords":72,"publishedAt":19},"01M734CYEMZFDR3KH6SW0JP8TD","implementing-network-traffic-baselining","Build network traffic baselines from NetFlow\u002FIPFIX data using Python pandas for statistical analysis, z-score anomaly detection, and hourly\u002Fdaily traffic pattern profiling","https:\u002F\u002Fgithub.com\u002Fyanacuti1121\u002FYana-AI\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fimplementing-network-traffic-baselining\u002FLICENSE","https:\u002F\u002Fgithub.com\u002FHoronomos-laps\u002FYana-AI\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fimplementing-network-traffic-baselining\u002FSKILL.md",[],[],{"skillNo":74,"name":75,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":77,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":19},"01M73ASZ6NJRJM44Z2P84NGQ3Q","detecting-evasion-techniques-in-endpoint-logs","Detects defense evasion techniques used by adversaries in endpoint logs including log tampering, timestomping, process injection, and security tool disabling. Use when investigating suspicious endpoint behavior, building detection rules for evasion tactics, or conducting threat hunting for stealthy adversary activity. Activates for requests involving evasion detection, defense evasion analysis, log tampering detection, or MITRE ATT&CK TA0005.","https:\u002F\u002Fgithub.com\u002Fyanacuti1121\u002FYana-AI\u002Fblob\u002Fmain\u002Fcore\u002Fskills\u002Fdetecting-evasion-techniques-in-endpoint-logs\u002FLICENSE","https:\u002F\u002Fgithub.com\u002FHoronomos-laps\u002FYana-AI\u002Fblob\u002Fmain\u002Fcore\u002Fskills\u002Fdetecting-evasion-techniques-in-endpoint-logs\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":85,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":19},"01M734AFNXD06Z78QRK0VKGT7Q","implementing-microsegmentation-with-guardicore","Implementing microsegmentation using Akamai Guardicore Segmentation to map application dependencies, create granular network policies, visualize east-west traffic flows, and enforce least-privilege communication between workloads across data centers and cloud.","https:\u002F\u002Fgithub.com\u002Fyanacuti1121\u002FYana-AI\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fimplementing-microsegmentation-with-guardicore\u002FLICENSE","https:\u002F\u002Fgithub.com\u002FHoronomos-laps\u002FYana-AI\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fimplementing-microsegmentation-with-guardicore\u002FSKILL.md",[],[],{"skillNo":90,"name":91,"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":92,"categories":93,"keywords":94,"publishedAt":19},"01M736TK27QMCXK0DVCH25SJN5","ramdisk-tmpfs-patterns","https:\u002F\u002Fgithub.com\u002FHoronomos-laps\u002FYana-AI\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Framdisk-tmpfs-patterns\u002FSKILL.md",[],[]]