构建优化

Mattakushi4322026-10-25查看 82复制 1316

何时激活:Vite 配置、捆绑优化、Tree Shaking、代码分割、模块联合、CDN、捆绑分析

Download (.md)

📘如何使用这个技能

  1. 1
    复制技能内容·点击上方「Copy SKILL.md」复制全部内容,或 Download 下载到本地
  2. 2
    打开你的 AI 客户端·支持 Claude Code、Trae、Cursor、ChatGPT、DeepSeek、Kimi 等任意 AI 助手
  3. 3
    粘贴为系统提示/知识文件·Claude Code:放入 .claude/skills/ 目录;普通对话:作为首条消息发送并说「请严格按这份技能文档执行」
  4. 4
    直接提出你的需求·AI 会按技能定义的工作流、格式和约束来处理,无需再解释背景

💡 提示:技能生效后,每次对话只需一句需求,AI 会按 SKILL.md 的流程执行。

SKILL.md3993 chars
---
name: build-optimization
description: "When to activate: Vite config, bundle optimization, tree shaking, code splitting, module federation, CDN, bundle analysis"
origin: zakr
metadata:
  namespace: zakr/devtools-pack
  version: 1.0.0
  category: frontend
  language: web
  platforms: [claude-code, codex, gemini-cli, cursor, aider, windsurf]
---
# Build Optimization Patterns

## Vite Configuration

```ts
// vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { visualizer } from 'rollup-plugin-visualizer';
import { compression } from 'vite-plugin-compression2';

export default defineConfig({
  plugins: [
    react(),
    compression({ algorithm: 'gzip' }),
    compression({ algorithm: 'brotliCompress', ext: '.br' }),
    visualizer({ open: false, gzipSize: true, filename: 'dist/stats.html' }),
  ],
  build: {
    target: 'es2020',
    minify: 'esbuild',
    sourcemap: true,
    rollupOptions: {
      output: {
        manualChunks: {
          'react-vendor': ['react', 'react-dom', 'react-router-dom'],
          'ui-vendor': ['@radix-ui/react-dialog', '@radix-ui/react-dropdown-menu'],
          'query': ['@tanstack/react-query'],
          'charts': ['recharts'],
        },
        chunkFileNames: 'assets/[name]-[hash].js',
        assetFileNames: 'assets/[name]-[hash].[ext]',
      }
    }
  },
  resolve: {
    alias: { '@': '/src' }
  }
});
```

## Tree Shaking

```js
// WRONG: imports entire library
import _ from 'lodash';
const result = _.groupBy(items, 'category');

// RIGHT: named import (tree-shakeable)
import { groupBy } from 'lodash-es';
const result = groupBy(items, 'category');

// Or use native
const result = Object.groupBy(items, i => i.category);

// Check if library is ESM (package.json "module" field)
// Use bundlephobia.com to check package size
```

## Code Splitting Strategies

```tsx
// Route-level splitting
import { lazy, Suspense } from 'react';
const Dashboard = lazy(() => import('./pages/Dashboard'));
const Settings   = lazy(() => import('./pages/Settings'));

// Component-level (heavy components)
const RichEditor = lazy(() => import('./components/RichEditor'));
const VideoPlayer = lazy(() => import('./components/VideoPlayer'));

// With loading boundary
<Suspense fallback={<PageSkeleton />}>
  <Dashboard />
</Suspense>

// Prefetch on hover/focus
function NavLink({ to, children }) {
  const prefetch = () => import(`./pages/${to}`);
  return <Link to={to} onMouseEnter={prefetch} onFocus={prefetch}>{children}</Link>;
}
```

## Bundle Analysis

```bash
# Vite: open stats.html after build
npx vite build && open dist/stats.html

# Webpack Bundle Analyzer
npx webpack-bundle-analyzer dist/stats.json

# Check what's in a package
npx bundlephobia lodash
```

## Module Federation (Vite)

```ts
// host/vite.config.ts
import federation from '@originjs/vite-plugin-federation';

export default defineConfig({
  plugins: [federation({
    name: 'host',
    remotes: {
      mfe_auth: 'http://localhost:3001/assets/remoteEntry.js',
      mfe_dashboard: 'http://localhost:3002/assets/remoteEntry.js',
    },
    shared: ['react', 'react-dom'],
  })]
});

// remote/vite.config.ts
export default defineConfig({
  plugins: [federation({
    name: 'mfe_auth',
    filename: 'remoteEntry.js',
    exposes: { './LoginForm': './src/components/LoginForm' },
    shared: ['react', 'react-dom'],
  })],
  build: { target: 'esnext' }
});
```

## CDN & Cache Headers

```nginx
# Long-term cache for hashed assets
location /assets/ {
  add_header Cache-Control "public, max-age=31536000, immutable";
}

# Short cache for HTML
location / {
  add_header Cache-Control "public, max-age=0, must-revalidate";
  try_files $uri /index.html;
}
```

## Environment-Based Optimization

```ts
// vite.config.ts
export default defineConfig(({ mode }) => ({
  define: {
    __DEV__: mode === 'development',
  },
  build: {
    minify: mode === 'production',
    sourcemap: mode !== 'production',
  }
}));
```
来源:skillsdirectory

评论0

登录后参与评论

还没有评论,来抢沙发吧