Elysia Tools

在一个清晰的工作台里浏览工具、案例、可视化和主题指南。

热门分类

专题

语言
ZHESPTRUFRDEEN

Elysia Tools

导航

构建工具

Rollup 配置示例

Rollup 构建工具配置示例,包括插件、优化、多构建设置和现代 JavaScript 打包

案例

这个案例集合中的条目

配置简单

基础 Rollup 配置

JavaScript 和 TypeScript 项目的基本 Rollup 配置,包含常用插件和优化

难度

4/10

预计时间

25 min

标签

rollup, build-tools, javascript, bundling

前置条件

JavaScript, Node.js, Build tools, Package managers

config
// Basic Rollup Configuration Examples
// rollup.config.js

import { defineConfig } from 'rollup';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import typescript from '@rollup/plugin-typescript';
import terser from '@rollup/plugin-terser';
import json from '@rollup/plugin-json';
import replace from '@rollup/plugin-replace';

// 1. Basic ES Module Build
var rollupConfig = defineConfig({
  input: 'src/index.js',
  output: {
    file: 'dist/bundle.js',
    format: 'es',
    sourcemap: true
  },
  plugins: [
    nodeResolve(),
    commonjs(),
    json()
  ]
});

// 2. TypeScript Configuration
var rollupConfig = defineConfig({
  input: 'src/index.ts',
  output: [
    {
      file: 'dist/index.esm.js',
      format: 'es',
      sourcemap: true
    },
    {
      file: 'dist/index.cjs.js',
      format: 'cjs',
      sourcemap: true
    }
  ],
  plugins: [
    typescript({
      tsconfig: './tsconfig.json',
      sourceMap: true,
      declaration: true,
      declarationDir: './dist',
      rootDir: './src'
    }),
    nodeResolve(),
    commonjs(),
    json()
  ]
});

// 3. Library Configuration
var rollupConfig = defineConfig({
  input: 'src/index.ts',
  output: [
    // ES Module for modern bundlers
    {
      file: 'dist/index.esm.js',
      format: 'es',
      sourcemap: true
    },
    // CommonJS for Node.js
    {
      file: 'dist/index.cjs.js',
      format: 'cjs',
      sourcemap: true,
      exports: 'named'
    },
    // UMD for browsers
    {
      file: 'dist/index.umd.js',
      format: 'umd',
      name: 'MyLibrary',
      sourcemap: true,
      globals: {
        'lodash': '_',
        'axios': 'axios'
      }
    }
  ],
  plugins: [
    typescript({
      tsconfig: './tsconfig.json',
      declaration: true,
      declarationDir: './dist'
    }),
    nodeResolve({
      preferBuiltins: true
    }),
    commonjs(),
    json(),
    replace({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development'),
      preventAssignment: true
    })
  ],
  external: ['lodash', 'axios']
});

// 4. React Component Library
var rollupConfig = defineConfig([
  // Development build
  {
    input: 'src/index.ts',
    output: {
      dir: 'dist',
      format: 'es',
      sourcemap: true
    },
    plugins: [
      typescript({
        tsconfig: './tsconfig.json',
        jsx: 'react-jsx',
        declaration: true,
        declarationDir: './dist'
      }),
      nodeResolve({
        extensions: ['.ts', '.tsx', '.js', '.jsx']
      }),
      commonjs(),
      json()
    ],
    external: ['react', 'react-dom']
  },
  // Production build with minification
  {
    input: 'src/index.ts',
    output: {
      dir: 'dist',
      format: 'es',
      sourcemap: false
    },
    plugins: [
      typescript({
        tsconfig: './tsconfig.json',
        jsx: 'react-jsx'
      }),
      nodeResolve({
        extensions: ['.ts', '.tsx', '.js', '.jsx']
      }),
      commonjs(),
      json(),
      terser({
        compress: {
          drop_console: true,
          drop_debugger: true
        },
        mangle: true,
        format: {
          comments: false
        }
      })
    ],
    external: ['react', 'react-dom']
  }
]);

// 5. Vue.js Application
import vue from 'rollup-plugin-vue';

var rollupConfig = defineConfig({
  input: 'src/main.js',
  output: {
    file: 'dist/bundle.js',
    format: 'es',
    sourcemap: true
  },
  plugins: [
    vue(),
    nodeResolve({
      extensions: ['.vue', '.js']
    }),
    commonjs(),
    json()
  ],
  external: ['vue']
});

// 6. Node.js Application
var rollupConfig = defineConfig({
  input: 'src/server.js',
  output: {
    file: 'dist/server.js',
    format: 'cjs',
    sourcemap: true
  },
  plugins: [
    nodeResolve({
      preferBuiltins: true
    }),
    commonjs(),
    json(),
    replace({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development'),
      preventAssignment: true
    })
  ],
  external: [
    'express',
    'cors',
    'helmet',
    'mongoose',
    'redis',
    'lodash'
  ]
});

// 7. Browser Application with Polyfills
var rollupConfig = defineConfig({
  input: 'src/index.js',
  output: {
    file: 'dist/bundle.js',
    format: 'iife',
    sourcemap: true,
    name: 'MyApp'
  },
  plugins: [
    nodeResolve({
      browser: true
    }),
    commonjs(),
    json(),
    replace({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development'),
      'process.env.API_URL': JSON.stringify(process.env.API_URL || 'http://localhost:3000'),
      preventAssignment: true
    })
  ]
});

// 8. Multi-entry Point Application
var rollupConfig = defineConfig({
  input: {
    main: 'src/main.js',
    admin: 'src/admin.js',
    worker: 'src/worker.js'
  },
  output: {
    dir: 'dist',
    format: 'es',
    entryFileNames: '[name].js',
    chunkFileNames: 'chunks/[name]-[hash].js',
    sourcemap: true
  },
  plugins: [
    nodeResolve(),
    commonjs(),
    json()
  ],
  manualChunks: {
    vendor: ['lodash', 'axios'],
    utils: ['src/utils/helper.js', 'src/utils/validator.js']
  }
});

// 9. Configuration with Environment Variables
const isProduction = process.env.NODE_ENV === 'production';
const isDevelopment = process.env.NODE_ENV === 'development';

var rollupConfig = defineConfig({
  input: 'src/index.ts',
  output: {
    file: isProduction ? 'dist/bundle.min.js' : 'dist/bundle.js',
    format: 'es',
    sourcemap: !isProduction
  },
  plugins: [
    typescript(),
    nodeResolve(),
    commonjs(),
    json(),
    ...(isProduction ? [
      terser({
        compress: {
          drop_console: true,
          drop_debugger: true,
          pure_funcs: ['console.log']
        },
        mangle: true
      })
    ] : [])
  ],
  ...(isProduction ? {
    treeshake: 'smallest'
  } : {
    treeshake: false
  })
});

// 10. CSS and Assets Configuration
import styles from 'rollup-plugin-styles';
import url from '@rollup/plugin-url';
import image from '@rollup/plugin-image';

var rollupConfig = defineConfig({
  input: 'src/index.js',
  output: {
    file: 'dist/bundle.js',
    format: 'es',
    sourcemap: true
  },
  plugins: [
    nodeResolve(),
    commonjs(),
    json(),
    styles({
      modules: true, // Enable CSS modules
      autoModules: {
        generateScopedName: '[local]___[hash:base64:5]'
      },
      sass: {
        includePaths: ['node_modules']
      }
    }),
    url({
      limit: 10 * 1024, // 10kb
      emitFiles: true
    }),
    image({
      output: 'dist/assets/images',
      publicPath: '/assets/images/'
    })
  ]
});

// 11. Plugin Configuration Examples

// Babel Plugin Configuration
import { babel } from '@rollup/plugin-babel';

var rollupConfig = defineConfig({
  input: 'src/index.js',
  output: {
    file: 'dist/bundle.js',
    format: 'es'
  },
  plugins: [
    babel({
      babelHelpers: 'bundled',
      exclude: 'node_modules/**',
      presets: [
        ['@babel/preset-env', {
          targets: {
            browsers: ['last 2 versions', 'ie >= 11']
          },
          modules: false
        }]
      ],
      plugins: [
        '@babel/plugin-proposal-class-properties',
        '@babel/plugin-proposal-object-rest-spread'
      ]
    }),
    nodeResolve(),
    commonjs()
  ]
});

// PostCSS Plugin Configuration
import postcss from 'rollup-plugin-postcss';
import autoprefixer from 'autoprefixer';
import cssnano from 'cssnano';

var rollupConfig = defineConfig({
  input: 'src/index.js',
  output: {
    file: 'dist/bundle.js',
    format: 'es'
  },
  plugins: [
    nodeResolve(),
    commonjs(),
    postcss({
      plugins: [
        autoprefixer(),
        cssnano({
          preset: 'default'
        })
      ],
      extract: true, // Extract CSS to separate file
      inject: false, // Don't inject CSS into head
      sourceMap: true
    })
  ]
});

// 12. Development and Production Scripts

// package.json scripts
{
  "scripts": {
    "build": "rollup -c",
    "build:dev": "rollup -c --environment NODE_ENV:development",
    "build:prod": "rollup -c --environment NODE_ENV:production",
    "watch": "rollup -c -w",
    "watch:dev": "rollup -c -w --environment NODE_ENV:development"
  }
}

// rollup.config.js with CLI flags
import { defineConfig } from 'rollup';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';

var rollupConfig = defineConfig(({ command, environment }) => {
  const isWatch = command === 'watch';
  const isProduction = environment?.NODE_ENV === 'production';

  return {
    input: 'src/index.js',
    output: {
      file: `dist/bundle${isProduction ? '.min' : ''}.js`,
      format: 'es',
      sourcemap: !isProduction
    },
    plugins: [
      nodeResolve(),
      commonjs(),
      ...(isProduction ? [
        require('@rollup/plugin-terser').default()
      ] : [])
    ],
    watch: {
      include: 'src/**'
    }
  };
});

// 13. Error Handling Configuration

var rollupConfig = defineConfig({
  input: 'src/index.js',
  output: {
    file: 'dist/bundle.js',
    format: 'es',
    sourcemap: true
  },
  plugins: [
    nodeResolve(),
    commonjs()
  ],
  onwarn: (warning, warn) => {
    // Ignore certain warnings
    if (warning.code === 'THIS_IS_UNDEFINED') return;
    if (warning.code === 'EVAL') return;

    // Log other warnings
    warn(warning);
  },
  ongenerate: (options, bundle) => {
    // Custom generation logic
    console.log(`Bundle size: ${bundle.bundle.size} bytes`);
  }
});

// 14. Performance Optimization Configuration

var rollupConfig = defineConfig({
  input: 'src/index.js',
  output: {
    file: 'dist/bundle.js',
    format: 'es',
    sourcemap: true,
    compact: true
  },
  plugins: [
    nodeResolve(),
    commonjs(),
    // Code splitting
    {
      name: 'vendor',
      async: () => ['lodash', 'axios', 'moment']
    },
    {
      name: 'utils',
      async: () => ['src/utils/**']
    }
  ],
  experimentalOptimizeChunks: true,
  treeshake: {
    moduleSideEffects: false,
    propertyReadSideEffects: false,
    unknownGlobalSideEffects: false
  }
});

// 15. Testing Configuration

// test-build.js - Build configuration for testing
var rollupConfig = defineConfig({
  input: 'src/index.test.js',
  output: {
    file: 'dist/test-bundle.js',
    format: 'cjs'
  },
  plugins: [
    nodeResolve(),
    commonjs(),
    json(),
    // Replace test environment variables
    replace({
      'process.env.NODE_ENV': JSON.stringify('test'),
      preventAssignment: true
    })
  ],
  external: ['jest', '@testing-library/react']
配置复杂

高级 Rollup 配置

复杂的 Rollup 配置,包括微前端、monorepo、性能优化和 CI/CD 集成

难度

8/10

预计时间

50 min

标签

rollup, advanced, build-tools, architecture

前置条件

Rollup basics, JavaScript/TypeScript, Build tools, CI/CD

config
// Advanced Rollup Configuration Examples
// Complex setups for enterprise applications

// 1. Microfrontends Architecture
import { defineConfig } from 'rollup';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import typescript from '@rollup/plugin-typescript';
import terser from '@rollup/plugin-terser';
import { generateSW } from 'rollup-plugin-workbox';

// Module Federation Configuration
var rollupConfig = defineConfig([
  // Shell application
  {
    input: 'src/shell/index.ts',
    output: {
      dir: 'dist/shell',
      format: 'es',
      sourcemap: true
    },
    plugins: [
      typescript({
        tsconfig: './src/shell/tsconfig.json'
      }),
      nodeResolve(),
      commonjs(),
      // Service Worker for PWA
      generateSW({
        globDirectory: 'dist/shell',
        globPatterns: ['**/*.{html,js,css,png}'],
        swDest: 'dist/shell/sw.js',
        runtimeCaching: [
          {
            urlPattern: /^https://api\.example\.com/,
            handler: 'NetworkFirst',
            options: {
              cacheName: 'api-cache',
              expiration: {
                maxEntries: 100,
                maxAgeSeconds: 60 * 60 * 24 // 24 hours
              }
            }
          }
        ]
      })
    ],
    external: ['react', 'react-dom']
  },
  // Microfrontend module
  {
    input: 'src/mfe/dashboard/index.ts',
    output: [
      {
        dir: 'dist/mfe/dashboard',
        format: 'es',
        sourcemap: true
      },
      {
        dir: 'dist/mfe/dashboard',
        format: 'system',
        sourcemap: true,
        name: 'dashboard'
      }
    ],
    plugins: [
      typescript({
        tsconfig: './src/mfe/dashboard/tsconfig.json'
      }),
      nodeResolve(),
      commonjs(),
      terser({
        compress: {
          drop_console: true
        }
      })
    ],
    external: ['react', 'react-dom', 'shared-utils']
  }
]);

// 2. Monorepo Configuration with Multiple Packages
import path from 'path';
import alias from '@rollup/plugin-alias';
import multiInput from 'rollup-plugin-multi-input';

// Root rollup.config.js for monorepo
const packages = [
  { name: 'core', entry: 'packages/core/src/index.ts' },
  { name: 'utils', entry: 'packages/utils/src/index.ts' },
  { name: 'components', entry: 'packages/components/src/index.ts' },
  { name: 'hooks', entry: 'packages/hooks/src/index.ts' }
];

export default packages.map(pkg => ({
  input: pkg.entry,
  output: [
    {
      file: `packages/${pkg.name}/dist/index.esm.js`,
      format: 'es',
      sourcemap: true
    },
    {
      file: `packages/${pkg.name}/dist/index.cjs.js`,
      format: 'cjs',
      sourcemap: true
    }
  ],
  plugins: [
    alias({
      entries: [
        {
          find: '@shared',
          replacement: path.resolve(__dirname, 'shared')
        },
        {
          find: '@core',
          replacement: path.resolve(__dirname, 'packages/core/src')
        }
      ]
    }),
    typescript({
      tsconfig: `packages/${pkg.name}/tsconfig.json`,
      declaration: true,
      declarationDir: `packages/${pkg.name}/dist`
    }),
    nodeResolve(),
    commonjs()
  ],
  external: ['react', 'react-dom']
}));

// 3. Complex Plugin Pipeline
import postcss from 'rollup-plugin-postcss';
import sass from 'rollup-plugin-sass';
import styles from 'rollup-plugin-styles';
import copy from 'rollup-plugin-copy';
import html from '@rollup/plugin-html';
import del from 'rollup-plugin-delete';

var rollupConfig = defineConfig({
  input: 'src/index.tsx',
  output: {
    file: 'dist/bundle.js',
    format: 'es',
    sourcemap: true
  },
  plugins: [
    // Clean dist directory
    del({ targets: 'dist/*' }),

    // Process SCSS/Sass files
    sass({
      insert: true, // Insert CSS into head
      output: 'dist/styles.css',
      outputStyle: 'compressed',
      sourceMap: true,
      includePaths: ['node_modules']
    }),

    // Process PostCSS (autoprefixer, minification)
    postcss({
      plugins: [
        require('autoprefixer')({
          browsers: ['last 2 versions', 'ie >= 11']
        }),
        require('cssnano')({
          preset: 'default'
        })
      ],
      extract: false, // Include CSS in JS bundle
      inject: true,
      minimize: true,
      sourceMap: true
    }),

    // Handle CSS modules
    styles({
      modules: {
        generateScopedName: '[name]__[local]___[hash:base64:5]'
      },
      use: [
        ['sass', {
          includePaths: ['src/styles']
        }]
      ]
    }),

    // Copy static assets
    copy({
      targets: [
        { src: 'src/public/**/*', dest: 'dist/public' },
        { src: 'src/assets/fonts/**/*', dest: 'dist/fonts' },
        { src: 'src/manifest.json', dest: 'dist' }
      ]
    }),

    // Generate HTML template
    html({
      template: ({ files }) => `
        <!DOCTYPE html>
        <html lang="en">
        <head>
          <meta charset="UTF-8">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <title>My Application</title>
          <link rel="manifest" href="/manifest.json">
          <script src="bundle.js" defer></script>
        </head>
        <body>
          <div id="root"></div>
        </body>
        </html>
      `
    }),

    // TypeScript processing
    typescript({
      tsconfig: './tsconfig.json',
      jsx: 'react-jsx',
      declaration: false,
      sourceMap: true
    }),

    // Node modules resolution
    nodeResolve({
      extensions: ['.ts', '.tsx', '.js', '.jsx']
    }),
    commonjs()
  ]
});

// 4. Performance Optimizations
import analyze from 'rollup-plugin-analyzer';
import visualizer from 'rollup-plugin-visualizer';
import { gzip } from 'rollup-plugin-gzip';

var rollupConfig = defineConfig({
  input: 'src/index.ts',
  output: {
    file: 'dist/bundle.js',
    format: 'es',
    sourcemap: true
  },
  plugins: [
    typescript(),
    nodeResolve(),
    commonjs(),

    // Analyze bundle size
    analyze({
      summaryOnly: true,
      limit: 10
    }),

    // Generate bundle visualization
    visualizer({
      filename: 'dist/stats.html',
      open: false,
      gzipSize: true
    }),

    // Create gzipped version
    gzip({
      additional: ['.css', '.svg', '.html']
    }),

    // Advanced code splitting
    {
      name: 'vendor',
      async: () => {
        const vendorDeps = await import('pkg-up');
        return vendorDeps.default({ cwd: process.cwd() }).map(dep => dep.name);
      }
    },
    {
      name: 'polyfills',
      async: () => ['core-js/stable', 'core-js/features']
    },

    // Tree shaking optimizations
    {
      treeshake: {
        moduleSideEffects: (id) => {
          if (id.includes('node_modules')) {
            return false;
          }
          return true;
        }
      }
    },

    // Minification with advanced options
    terser({
      compress: {
        dead_code: true,
        drop_console: true,
        drop_debugger: true,
        pure_funcs: ['console.log', 'console.info'],
        passes: 3
      },
      mangle: {
        properties: {
          regex: /^_/ // Only mangle private properties
        }
      },
      format: {
        comments: false,
        ascii_only: true
      }
    })
  ]
});

// 5. Plugin Development Example
import { Plugin } from 'rollup';

// Custom plugin for analytics
function analyticsPlugin(options = {}) {
  const { endpoint = '/analytics', apiKey = '' } = options;

  return {
    name: 'analytics',
    buildStart() {
      console.log('Analytics plugin initialized');
    },
    generateBundle(options, bundle) {
      const analytics = {
        buildTime: new Date().toISOString(),
        bundleSize: bundle.bundle.size,
        entryCount: Object.keys(bundle).length,
        modules: Object.values(bundle).map(chunk => ({
          name: chunk.fileName,
          size: chunk.code.length
        }))
      };

      // Send analytics data (mock implementation)
      console.log('Analytics data:', analytics);

      // In a real plugin, you would send this to your analytics endpoint
      // await fetch(endpoint, {
      //   method: 'POST',
      //   headers: { 'Authorization': `Bearer ${apiKey}` },
      //   body: JSON.stringify(analytics)
      // });
    }
  };
}

var rollupConfig = defineConfig({
  input: 'src/index.ts',
  output: {
    file: 'dist/bundle.js',
    format: 'es'
  },
  plugins: [
    typescript(),
    nodeResolve(),
    commonjs(),
    analyticsPlugin({
      endpoint: process.env.ANALYTICS_ENDPOINT,
      apiKey: process.env.ANALYTICS_API_KEY
    })
  ]
});

// 6. Conditional Configuration Based on Environment
import { defineConfig } from 'rollup';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import typescript from '@rollup/plugin-typescript';
import terser from '@rollup/plugin-terser';
import { createRequire } from 'module';

const require = createRequire(import.meta.url);
const pkg = require('./package.json');

const isProduction = process.env.NODE_ENV === 'production';
const isDevelopment = process.env.NODE_ENV === 'development';
const isTest = process.env.NODE_ENV === 'test';

function createConfig(env = process.env.NODE_ENV) {
  const commonPlugins = [
    typescript({
      tsconfig: './tsconfig.json'
    }),
    nodeResolve(),
    commonjs()
  ];

  const baseConfig = {
    input: pkg.source || 'src/index.ts',
    external: Object.keys(pkg.peerDependencies || {}),
    plugins: [...commonPlugins]
  };

  switch (env) {
    case 'production':
      return {
        ...baseConfig,
        output: [
          {
            file: pkg.main || 'dist/index.js',
            format: 'cjs',
            sourcemap: false
          },
          {
            file: pkg.module || 'dist/index.esm.js',
            format: 'es',
            sourcemap: false
          }
        ],
        plugins: [
          ...baseConfig.plugins,
          terser({
            compress: {
              drop_console: true,
              drop_debugger: true
            }
          })
        ],
        treeshake: 'smallest'
      };

    case 'development':
      return {
        ...baseConfig,
        output: {
          file: 'dist/bundle.dev.js',
          format: 'es',
          sourcemap: 'inline'
        },
        watch: {
          include: 'src/**',
          clearScreen: false
        }
      };

    case 'test':
      return {
        ...baseConfig,
        output: {
          file: 'dist/bundle.test.js',
          format: 'cjs'
        },
        plugins: [
          ...baseConfig.plugins,
          // Add test-specific plugins
          {
            name: 'test-replacements',
            transform(code, id) {
              if (id.endsWith('.test.ts')) {
                return code.replace(
                  'process.env.API_URL',
                  JSON.stringify('http://localhost:3001')
                );
              }
              return code;
            }
          }
        ],
        external: [
          ...baseConfig.external,
          'jest',
          '@testing-library/react',
          '@testing-library/jest-dom'
        ]
      };

    default:
      return baseConfig;
  }
}

var rollupConfig = defineConfig([
  createConfig('production'),
  createConfig('development'),
  createConfig('test')
]);

// 7. CI/CD Integration Configuration
import { defineConfig } from 'rollup';
import execute from 'rollup-plugin-execute';

var rollupConfig = defineConfig({
  input: 'src/index.ts',
  output: {
    file: 'dist/bundle.js',
    format: 'es',
    sourcemap: true
  },
  plugins: [
    typescript(),
    nodeResolve(),
    commonjs(),

    // Run tests before build
    {
      name: 'run-tests',
      buildStart() {
        return execute('npm test');
      }
    },

    // Lint code
    {
      name: 'lint-code',
      buildStart() {
        return execute('npm run lint');
      }
    },

    // Type checking
    {
      name: 'type-check',
      buildStart() {
        return execute('npx tsc --noEmit');
      }
    }
  ]
});

// 8. Bundle Analysis and Optimization
import { createRequire } from 'module';
import path from 'path';

const require = createRequire(import.meta.url);

var rollupConfig = defineConfig({
  input: 'src/index.ts',
  output: {
    file: 'dist/bundle.js',
    format: 'es'
  },
  plugins: [
    // Bundle analysis
    {
      name: 'bundle-analyzer',
      generateBundle(options, bundle) {
        const totalSize = bundle['bundle.js'].code.length;
        const sizeReport = {
          total: totalSize,
          compressed: totalSize * 0.3, // Estimated gzip size
          chunks: Object.keys(bundle).map(name => ({
            name,
            size: bundle[name].code.length,
            percentage: (bundle[name].code.length / totalSize * 100).toFixed(2)
          }))
        };

        // Write analysis report
        require('fs').writeFileSync(
          'dist/bundle-analysis.json',
          JSON.stringify(sizeReport, null, 2)
        );

        console.log('Bundle Analysis:');
        console.log(`Total size: ${(totalSize / 1024).toFixed(2)} KB`);
        console.log(`Compressed: ${(sizeReport.compressed / 1024).toFixed(2)} KB`);
      }
    },

    // Generate dependency report
    {
      name: 'dependency-report',
      buildStart() {
        const pkg = require('./package.json');
        const dependencies = {
          ...pkg.dependencies,
          ...pkg.devDependencies
        };

        const report = {
          name: pkg.name,
          version: pkg.version,
          totalDependencies: Object.keys(dependencies).length,
          dependencies: Object.entries(dependencies).map(([name, version]) => ({
            name,
            version,
            type: pkg.dependencies[name] ? 'production' : 'development'
          }))
        };

        require('fs').writeFileSync(
          'dist/dependencies.json',
          JSON.stringify(report, null, 2)
        );
      }
    }
  ]
});

// 9. Advanced Error Handling and Reporting
var rollupConfig = defineConfig({
  input: 'src/index.ts',
  output: {
    file: 'dist/bundle.js',
    format: 'es'
  },
  plugins: [
    typescript(),
    nodeResolve(),
    commonjs(),

    // Error handling plugin
    {
      name: 'error-reporter',
      buildError(error) {
        // Send error to monitoring service
        if (process.env.ERROR_WEBHOOK) {
          require('node-fetch')(process.env.ERROR_WEBHOOK, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
              error: error.message,
              stack: error.stack,
              timestamp: new Date().toISOString()
            })
          }).catch(console.error);
        }

        // Write error log
        require('fs').writeFileSync(
          'dist/build-error.log',
          `\$${new Date().toISOString()}: ${error.stack}\n`
        );

        throw error;
      }
    },

    // Warning handler
    {
      name: 'warning-handler',
      onwarn: (warning, warn) => {
        // Categorize warnings
        const warningCategories = {
          treeshake: warning.code?.startsWith('TREE_SHAKE_'),
          module: warning.code?.startsWith('MODULE_'),
      };

        const category = Object.keys(warningCategories).find(key =>
          warningCategories[key]
        );

        // Log warnings with context
        console.log(`[${category || 'GENERAL'}] ${warning.message}`);

        // Save warnings to file
        const warningLog = {
          timestamp: new Date().toISOString(),
          category: category || 'general',
          code: warning.code,
          message: warning.message,
          source: warning.source
        };

        const existingWarnings = require('fs').existsSync('dist/warnings.json')
          ? JSON.parse(require('fs').readFileSync('dist/warnings.json'))
          : [];

        existingWarnings.push(warningLog);
        require('fs').writeFileSync(
          'dist/warnings.json',
          JSON.stringify(existingWarnings, null, 2)
        );

        // Decide whether to suppress warning
        if (warning.code === 'THIS_IS_UNDEFINED') return;
        if (warning.code === 'EVAL') return;

        warn(warning);
      }
    }
  ]
});

// 10. Runtime Configuration
var rollupConfig = defineConfig(({ command, getModuleInfo }) => {
  const isWatch = command === 'watch';
  const moduleInfo = getModuleInfo();

  return {
    input: 'src/index.ts',
    output: {
      file: 'dist/bundle.js',
      format: 'es',
      sourcemap: true,
      compact: !isWatch
    },
    plugins: [
      typescript(),
      nodeResolve(),
      commonjs(),
      {
        name: 'runtime-logger',
        buildStart(options) {
          console.log('Rollup configuration:');
          console.log(`  Input: ${options.input}`);
          console.log(`  Format: ${this.output?.format}`);
          console.log(`  Watch mode: ${isWatch}`);
          console.log(`  Module count: ${moduleInfo?.moduleIds?.length || 0}`);
        },
        generateBundle(options, bundle) {
          const stats = {
            files: Object.keys(bundle),
            totalSize: Object.values(bundle).reduce((sum, file) => sum + file.code.length, 0),
            buildTime: new Date().toISOString()
          };

          console.log('Build completed:', stats);

          // Write build stats
          require('fs').writeFileSync(
            'dist/build-stats.json',
            JSON.stringify(stats, null, 2)
          );
        }
      }
    ],
    ...(isWatch && {
      watch: {
        include: 'src/**',
        exclude: 'node_modules/**'
      }
    })
  };
});

工具

经常与该案例搭配使用的工具

相关内容

相关案例集合

相关内容

相关专题

专题

环境变量与配置格式治理工作流

在不暴露密钥的前提下解析、校验、转换、合并并比较配置,记录事实来源。

专题

容器发布前的 Dockerfile 与环境配置审查

检查 Dockerfile 规则、镜像引用格式与环境变量重复键,解释预发布和生产配置差异,形成可核对的容器发布记录。

专题

自托管抽奖组件配置复核、嵌入测试与上线交付

复核转盘、刮刮卡或盲盒的配置与商家接口样例,检查可读性和移动端布局,交付版本明确的组件文件及真实浏览器验收记录。

专题

JSON 规范化与数据交换工作流

把结构化来源转换为经过核对的 JSON 表示,再按下游需求导出为表格、配置、文档、API、XML、CSON、EDN、BSON 或 UBJSON。

首页
工具3206
案例593
可视化468
文件查看器103
专题236
标签333
图像、音频与视频657

图像、音频、视频处理、转换与优化工具

数学、日期与金融645

计算器、数值计算、日期逻辑、统计与金融工具

设计与颜色298

颜色、版式、图形、视觉样式与设计辅助工具

文本与写作209

写作、清洗、格式化、提取与文本分析工具

开发与 Web193

开发者工具、网络处理、Web 调试与自动化辅助工具

转换与编码175

格式、文件、压缩包、单位与编码转换工具

长文改编 X 串文与 LinkedIn 帖子的事实复核与交付
Markdown 互动课件审校、离线演示与交付
小房间家具布局复核与搬入方案交付
FLAC/WAV 无损音源疑点筛查与证据交付
自托管抽奖组件配置复核、嵌入测试与上线交付

© 2026 Elysia Tools. 保留所有权利。

文档价格关于我们服务条款隐私政策Cookie 政策联系我们

Format Conversion

SSH配置解析器

解析和转换SSH配置文件为JSON格式

Development

配置文件语义 Diff

比较 JSON、YAML、TOML 和 dotenv 配置,按键路径显示变化并忽略排序与格式噪声。

Development

环境配置差异可视化器

对 JSON、YAML、TOML 与 ENV 配置进行跨环境对比,高亮漂移项、缺失项,并给出清洗建议。

Format Conversion

TOML / INI / HCL / .env / Nix / dotenv / Kubernetes ConfigMap / Secret 配置格式桥

在 dotenv .env、TOML、INI、Java .properties、YAML、JSON、HCL(Terraform/Vagrant 原生语法)与 Nix 属性集之间转换配置,并可输出 Kubernetes ConfigMap / Secret 清单;保留 ${VAR} / {{var}} 模板占位符与 envsubst 风格插值、记录类型推断来源(string/int/float/bool/list)、HCL 块标签自动折叠为嵌套键,往返 diff 突出非等价设置(丢失键、类型变化、值改写),输出对 Kustomize 补丁友好的 YAML。

Format Conversion

WireGuard/OpenVPN 到 Clash 与 sing-box 配置桥接器

将粘贴的 WireGuard 或 OpenVPN 客户端文本转换为 Mihomo/Clash YAML 或 sing-box JSON,并报告密钥字段;请勿分享私钥

Development

注释文档提取器

从JavaScript/TypeScript、Python和Java源代码中提取和解析文档

构建工具

esbuild 打包工具示例

现代JavaScript打包工具示例,包括配置、插件、优化和集成工作流

构建工具

Webpack 配置示例

Webpack配置示例,包括基础设置、优化、加载器、插件和现代webpack模式

构建工具

Rollup 插件开发

Rollup插件开发示例,包括自定义插件、转换和打包模式

构建工具

Vite 示例

Vite构建工具示例 - 现代开发服务器、HMR、打包和插件系统

构建工具

Grunt 构建工具

Grunt JavaScript任务运行器示例,包括自动化、构建流程和部署工作流

构建工具

Rollup 插件开发

Rollup插件开发示例,包括自定义插件、转换和打包模式