Token导航 LogoToken导航

Agent Skill · 开发

vite-bundle-optimization(vite 捆绑优化)

vite-bundle-optimization 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

vite-bundle-optimization 是开发类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为操作浏览器;许可证信息还不明确,第三方扫描已通过,按安装量在开发类的 21,746 个 Skill 里排第 5,717。

总安装 5,856周安装 249GitHub Stars 173下载 2,052核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:vite-bundle-optimization(vite 捆绑优化)
来源仓库:https://github.com/patternsdev/skills
仓库路径:skills/vite-bundle-optimization
安装命令:
npx skills add https://github.com/patternsdev/skills --skill vite-bundle-optimization
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/patternsdev/skills --skill vite-bundle-optimization

这个 Skill 是做什么的

开发类 Skill 面向写代码、改代码和排查问题,一般会读写仓库文件,部分还会执行构建或测试命令。

用于处理 GitHub 仓库、Issue 和 Pull Request 信息,适合协作事项整理。可帮助 Agent 围绕代码变更和仓库状态进行梳理,提升开发流程效率。

安装命令:npx skills add https://github.com/patternsdev/skills --skill vite-bundle-optimization 使用前建议确认权限范围和维护状态,避免触发联网或命令执行。注意检查是否会读写文件或修改项目结构。

来源仓库内路径:skills/vite-bundle-optimization

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/patternsdev/skills --skill vite-bundle-optimiz…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要操作浏览器,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

vite-bundle-optimization 怎么安装?

在终端执行 npx skills add https://github.com/patternsdev/skills --skill vite-bundle-optimization。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

vite-bundle-optimization 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

vite-bundle-optimization 需要什么权限?

权限级别是操作浏览器。该 Skill 可能涉及浏览器控制能力,使用时可能读取或操作网页内容,需要在受控环境中确认权限边界。

vite-bundle-optimization 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

vite-bundle-optimization 用的人多吗?

公开数据是累计安装 5,856 次,近一周安装 249 次,下载 2,052 次,GitHub 173 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

vite-bundle-optimization 安全吗?

第三方扫描结果为通过,但这只覆盖已知的静态检查项,不能替代自己读一遍源码和安装命令。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 第三方扫描已通过,常见的高风险行为没有命中。

先想清楚的地方

  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理开发类任务、又不想每次都手写提示词的人。

不太适合

  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

开发类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
skill-vetter

技能审查员 · OpenClaw

8,779,018986操作浏览器MIT-0通过
ontology

本体论 · OpenClaw

6,636,960576只读MIT-0通过
entra-app-registration

内部应用程序注册 · Codex、Claude

6,631,872764接触敏感数据未明确通过
entra-app-registration

内部应用程序注册 · Codex、Claude

3,757,680201接触敏感数据未明确通过
nano-banana-pro

纳米香蕉专业版 · OpenClaw

3,526,898364接触敏感数据MIT-0有提醒
vite-bundle-optimization

vite 捆绑优化 · 本页

5,856173操作浏览器未明确通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

Vite Bundle Optimization

Table of Contents

Production-ready patterns for optimizing bundle size and build performance in Vite + React applications. These patterns leverage Vite's architecture (native ESM in dev, Rollup in production) to deliver smaller, faster bundles.

When to Use

Reference these patterns when:

  • Setting up a new Vite + React project for production
  • Analyzing bundle size with npx vite-bundle-visualizer
  • Build times are slow or bundles are unexpectedly large
  • Migrating from webpack/CRA to Vite
  • Optimizing Core Web Vitals (LCP, FID/INP, CLS)

Instructions

  • Apply these patterns during project setup, build configuration, and bundle size reviews. When you see large bundles or slow builds, diagnose with npx vite-bundle-visualizer and apply the relevant pattern.

Details

Overview

Vite uses esbuild for dependency pre-bundling and development transforms, and Rollup for production builds. Understanding this dual architecture is key to optimizing effectively. The patterns below are ordered by impact.


1. Avoid Barrel File Imports

Impact: CRITICAL — Can add 200-800ms to startup and 2-4s to dev server boot.

Barrel files (index.ts that re-export from many modules) force bundlers to load the entire module graph even when you only use one export. This is the #1 bundle size issue in React apps.

Avoid — imports entire library through barrel:

import { Button, TextField } from '@/components'
// Loads ALL components in the barrel, even unused ones

import { Check, X, Menu } from 'lucide-react'
// Loads all 1,500+ icons (~2.8s in dev)

Prefer — direct imports:

import { Button } from '@/components/Button'
import { TextField } from '@/components/TextField'

import Check from 'lucide-react/dist/esm/icons/check'
import X from 'lucide-react/dist/esm/icons/x'
import Menu from 'lucide-react/dist/esm/icons/menu'

Auto-fix with vite-plugin-barrel:

// vite.config.ts
import barrel from 'vite-plugin-barrel'

export default defineConfig({
  plugins: [
    react(),
    barrel({
      packages: ['lucide-react', '@mui/material', '@mui/icons-material'],
    }),
  ],
})

This transforms barrel imports into direct imports at build time, giving you ergonomic syntax with direct-import performance.

Commonly affected libraries: lucide-react, @mui/material, @mui/icons-material, @tabler/icons-react, react-icons, @radix-ui/react-*, lodash, date-fns, rxjs.


2. Configure Manual Chunk Splitting

Impact: HIGH — Better caching, parallel loading, smaller initial bundle.

Vite's default chunking puts all vendor code into one file. Split it so that frequently-changing app code doesn't invalidate the vendor cache.

// vite.config.ts
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
  build: {
    rollupOptions: {
      output: {
        manualChunks: {
          // Core React — rarely changes
          'vendor-react': ['react', 'react-dom'],
          // Router — changes infrequently
          'vendor-router': ['react-router-dom'],
          // Data layer — changes occasionally
          'vendor-query': ['@tanstack/react-query'],
          // UI framework — changes with design updates
          'vendor-ui': ['@radix-ui/react-dialog', '@radix-ui/react-dropdown-menu'],
        },
      },
    },
  },
})

For more dynamic splitting based on module paths:

manualChunks(id) {
  if (id.includes('node_modules')) {
    if (id.includes('react-dom')) return 'vendor-react'
    if (id.includes('react-router')) return 'vendor-router'
    if (id.includes('@tanstack')) return 'vendor-query'
    return 'vendor' // everything else
  }
},

3. Dynamic Imports for Route-Level Code Splitting

Impact: HIGH — Load only the code needed for the current page.

Use React.lazy() with dynamic imports to split each route into its own chunk.

import { lazy, Suspense } from 'react'
import { BrowserRouter, Routes, Route } from 'react-router-dom'

const Home = lazy(() => import('./pages/Home'))
const Dashboard = lazy(() => import('./pages/Dashboard'))
const Settings = lazy(() => import('./pages/Settings'))

function App() {
  return (
    <BrowserRouter>
      <Suspense fallback={<PageSkeleton />}>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/dashboard" element={<Dashboard />} />
          <Route path="/settings" element={<Settings />} />
        </Routes>
      </Suspense>
    </BrowserRouter>
  )
}

Vite automatically creates separate chunks for each lazy import. Name them for easier debugging:

const Dashboard = lazy(() =>
  import(/* webpackChunkName: "dashboard" */ './pages/Dashboard')
)

4. Lazy-Load Heavy Components Below the Fold

Impact: HIGH — Reduces initial bundle for faster LCP.

Components that aren't visible on initial load (modals, charts, editors, maps) should be lazy-loaded.

import { lazy, Suspense, useState } from 'react'

const RichTextEditor = lazy(() => import('./components/RichTextEditor'))
const ChartPanel = lazy(() => import('./components/ChartPanel'))

function ArticlePage() {
  const [editing, setEditing] = useState(false)

  return (
    <article>
      <h1>Article Title</h1>
      <p>Content visible immediately...</p>

      {editing && (
        <Suspense fallback={<EditorSkeleton />}>
          <RichTextEditor />
        </Suspense>
      )}

      <Suspense fallback={<ChartSkeleton />}>
        <ChartPanel />
      </Suspense>
    </article>
  )
}

5. Defer Third-Party Scripts

Impact: HIGH — Analytics, tracking, and widgets shouldn't block rendering.

Load non-critical third-party scripts after the page is interactive.

Avoid — blocks initial render:

// main.tsx
import * as Sentry from '@sentry/react'
import posthog from 'posthog-js'

Sentry.init({ dsn: '...' })
posthog.init('...')

Prefer — load after hydration/mount:

// main.tsx — defer to idle time
function initThirdParty() {
  import('@sentry/react').then(Sentry => {
    Sentry.init({ dsn: import.meta.env.VITE_SENTRY_DSN })
  })
  import('posthog-js').then(({ default: posthog }) => {
    posthog.init(import.meta.env.VITE_POSTHOG_KEY)
  })
}

if ('requestIdleCallback' in window) {
  requestIdleCallback(initThirdParty)
} else {
  setTimeout(initThirdParty, 2000)
}

For external script tags, use defer or dynamically inject them:

function loadScript(src: string) {
  const script = document.createElement('script')
  script.src = src
  script.async = true
  document.body.appendChild(script)
}

6. Preload Critical Assets on User Intent

Impact: MEDIUM — Eliminates perceived latency on navigation.

Start loading a route's code when the user signals intent (hover, focus) rather than waiting for the click.

function NavLink({ to, children }: { to: string; children: React.ReactNode }) {
  const preload = () => {
    // Vite creates a module preload for dynamic imports
    switch (to) {
      case '/dashboard':
        import('./pages/Dashboard')
        break
      case '/settings':
        import('./pages/Settings')
        break
    }
  }

  return (
    <Link to={to} onMouseEnter={preload} onFocus={preload}>
      {children}
    </Link>
  )
}

For <link rel="modulepreload"> in the HTML head:

<!-- Preload critical route chunks -->
<link rel="modulepreload" href="/assets/Home-abc123.js" />

Vite automatically adds <link rel="modulepreload"> for entry chunks. Add manual preloads for routes you know users will visit next.


7. Configure Dependency Pre-Bundling

Impact: MEDIUM — Faster dev server startup and page loads.

Vite pre-bundles node_modules dependencies using esbuild. Configure it to handle edge cases.

// vite.config.ts
export default defineConfig({
  optimizeDeps: {
    // Force pre-bundle these (useful for CJS deps or deep imports)
    include: [
      'react',
      'react-dom',
      'react-router-dom',
      '@tanstack/react-query',
      'date-fns/format',
      'date-fns/parseISO',
    ],
    // Skip pre-bundling for these (already ESM, or causes issues)
    exclude: ['@vite-pwa/assets-generator'],
  },
})

If you see slow page loads in dev with many small requests, it's usually because a dependency isn't pre-bundled. Add it to include.


8. Enable Compression

Impact: MEDIUM — 60-80% smaller transfer sizes.

Vite doesn't compress by default. Add the compression plugin for production.

// vite.config.ts
import viteCompression from 'vite-plugin-compression'

export default defineConfig({
  plugins: [
    react(),
    viteCompression({ algorithm: 'gzip' }),
    viteCompression({ algorithm: 'brotliCompress' }),
  ],
})

This generates .gz and .br files alongside your assets. Configure your server (Nginx, Cloudflare, Vercel) to serve them.


9. Analyze Your Bundle Regularly

Impact: INFORMATIONAL — Catch size regressions before they ship.

Run the bundle visualizer after every significant dependency change.

npx vite-bundle-visualizer

Or add it to your build script:

{
  "scripts": {
    "build": "vite build",
    "analyze": "vite build && npx vite-bundle-visualizer"
  }
}

What to look for:

  • Any single chunk > 200KB gzipped — consider splitting
  • Duplicate libraries loaded in multiple chunks
  • Full library loaded when only a few functions are used
  • node_modules code that could be dynamically imported

10. Use import.meta.env for Dead Code Elimination

Impact: LOW-MEDIUM — Removes unused code paths in production.

Vite replaces import.meta.env.* at build time, allowing Rollup to tree-shake dead branches.

// This code is completely removed in production
if (import.meta.env.DEV) {
  console.log('Debug info:', data)
  window.__DEBUG_DATA__ = data
}

// Feature flags eliminated at build time
if (import.meta.env.VITE_FEATURE_NEW_DASHBOARD === 'true') {
  // Only included when flag is set
  initNewDashboard()
}

Define custom env variables in .env files:

# .env.production
VITE_FEATURE_NEW_DASHBOARD=true
VITE_API_URL=https://api.example.com

11. Optimize Images and Static Assets

Impact: MEDIUM — Images are typically the largest assets.

Configure asset handling in Vite:

// vite.config.ts
export default defineConfig({
  build: {
    assetsInlineLimit: 4096, // Inline assets < 4KB as base64
    rollupOptions: {
      output: {
        assetFileNames: (assetInfo) => {
          // Organize assets by type
          if (/\.(png|jpe?g|gif|svg|webp|avif)$/.test(assetInfo.name ?? '')) {
            return 'images/[name]-[hash][extname]'
          }
          if (/\.(woff2?|ttf|eot)$/.test(assetInfo.name ?? '')) {
            return 'fonts/[name]-[hash][extname]'
          }
          return 'assets/[name]-[hash][extname]'
        },
      },
    },
  },
})

Use vite-plugin-image-optimizer for automatic image compression:

import { ViteImageOptimizer } from 'vite-plugin-image-optimizer'

export default defineConfig({
  plugins: [
    react(),
    ViteImageOptimizer({
      png: { quality: 80 },
      jpeg: { quality: 80 },
      webp: { quality: 80 },
    }),
  ],
})

12. Configure Dev Server Proxy for API Development

Impact: MEDIUM — Eliminates CORS issues and simplifies local development.

Vite SPAs typically talk to a separate backend API. Configure server.proxy to forward API requests during development, avoiding CORS and matching production URL patterns.

// vite.config.ts
export default defineConfig({
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:3001',
        changeOrigin: true,
      },
      '/auth': {
        target: 'http://localhost:3001',
        changeOrigin: true,
      },
      // WebSocket support for real-time features
      '/ws': {
        target: 'ws://localhost:3001',
        ws: true,
      },
    },
  },
})

In your app code, use relative paths (fetch('/api/users')) — they hit Vite's dev server which proxies to your backend. In production, configure your reverse proxy (Nginx, Caddy) to do the same routing.


13. Add PWA Support with vite-plugin-pwa

Impact: MEDIUM — Offline capability, installability, and cached assets for Vite SPAs.

For SPAs that need offline support or installability, vite-plugin-pwa handles service worker generation, precaching, and manifest creation.

// vite.config.ts
import { VitePWA } from 'vite-plugin-pwa'

export default defineConfig({
  plugins: [
    react(),
    VitePWA({
      registerType: 'autoUpdate',
      includeAssets: ['favicon.svg', 'robots.txt'],
      manifest: {
        name: 'My App',
        short_name: 'App',
        theme_color: '#ffffff',
        icons: [
          { src: '/icon-192.png', sizes: '192x192', type: 'image/png' },
          { src: '/icon-512.png', sizes: '512x512', type: 'image/png' },
        ],
      },
      workbox: {
        globPatterns: ['**/*.{js,css,html,ico,png,svg,woff2}'],
        runtimeCaching: [
          {
            urlPattern: /^https:\/\/api\./,
            handler: 'NetworkFirst',
            options: { cacheName: 'api-cache', expiration: { maxEntries: 50 } },
          },
        ],
      },
    }),
  ],
})

Use registerType: 'autoUpdate' for apps that should silently update. Use registerType: 'prompt' to show users an update notification.


14. Choose a CSS Strategy

Impact: MEDIUM — Vite supports multiple CSS approaches with zero config.

Vite handles CSS Modules, PostCSS, and preprocessors out of the box. Choose based on your needs:

CSS Modules — scoped styles, no runtime cost, built into Vite:

// Button.module.css → automatically scoped
import styles from './Button.module.css'

function Button({ children }: { children: React.ReactNode }) {
  return <button className={styles.primary}>{children}</button>
}

Tailwind CSS — utility-first, works with Vite's PostCSS support:

// vite.config.ts — no plugin needed, Tailwind uses PostCSS
// Just install tailwindcss and add postcss.config.js

// postcss.config.js
export default {
  plugins: {
    '@tailwindcss/postcss': {},
  },
}

CSS-in-JS considerations: Libraries like styled-components and Emotion add runtime overhead. For Vite SPAs prioritizing performance, prefer CSS Modules or Tailwind. If you need CSS-in-JS, consider zero-runtime options like Vanilla Extract or Panda CSS.


15. Set Up the React Compiler as a Vite Plugin

Impact: HIGH — Automatic memoization eliminates manual useMemo, useCallback, and React.memo.

The React Compiler analyzes your components and auto-inserts memoization. In a Vite project, add it as a Babel plugin:

npm install -D babel-plugin-react-compiler
// vite.config.ts
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [
    react({
      babel: {
        plugins: ['babel-plugin-react-compiler'],
      },
    }),
  ],
})

Once enabled, you can gradually remove manual useMemo, useCallback, and React.memo calls — the compiler handles them automatically. Verify behavior is preserved by running your test suite after enabling.

The compiler requires React 19. It's opt-in and can be enabled per-file with a 'use memo' directive if you prefer incremental adoption.


Source

Patterns from patterns.dev — Vite-specific optimization guidance for the broader React web engineering community.

平台分布

Codex

35.65%
按下载量换算732

Claude

29.8%
按下载量换算611

Cursor

19.48%
按下载量换算400

Gemini CLI

9.48%
按下载量换算195

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

操作浏览器

该 Skill 可能涉及浏览器控制能力,使用时可能读取或操作网页内容,需要在受控环境中确认权限边界。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills