Elysia Tools

Durchsuche Tools, Beispiele, visuelle Erklärungen und Themenguides an einem klaren Ort.

Beliebte Kategorien

Themen

Sprache
ZHESPTRUFRDEEN

Elysia Tools

Mobile Navigation

Build-Tools

Rollup: Ausgaben, Modulformate und externe Globals | Elysia Tools

Bearbeiten Sie drei begrenzte Rollup-Beispiele mit festen Eingaben und prüfbaren Ergebnissen.

Beispiele

Einträge in dieser Sammlung

KonfigurationEinfach

Basis-Rollup-Konfiguration

Grundlegende Rollup-Konfiguration für JavaScript- und TypeScript-Projekte mit gängigen Plugins und Optimierungen

Schwierigkeit

4/10

Geschätzte Zeit

25 min

Schlagwörter

rollup, build-tools, javascript, bundling

Voraussetzungen

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']
KonfigurationKomplex

Erweiterte Rollup-Konfiguration

Komplexe Rollup-Konfigurationen einschließlich Microfrontends, Monorepos, Performance-Optimierung und CI/CD-Integration

Schwierigkeit

8/10

Geschätzte Zeit

50 min

Schlagwörter

rollup, advanced, build-tools, architecture

Voraussetzungen

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/**'
      }
    })
  };
});

Werkzeuge

Tools, die oft mit diesem Beispiel genutzt werden

Verwandt

Verwandte Beispielsammlungen

Verwandt

Verwandte Themen

Leitfaden zur Tool-Nutzung

Kontext zum Verständnis dieser Beispielsammlung

Überblick

Nutzen Sie „Basis-Rollup-Konfiguration“ für diese Übungen. Folgen Sie nur dem genannten Block; andere Karten behandeln eigene Sprachmerkmale und Abhängigkeiten.

Das kleinste Beispiel wählen

Genannte Konfiguration nur lesen, nicht importieren. Hypothetische Literale brauchen keine Builds, Hooks, Installation oder Dateioperation.

Wiederholte rollupConfig-Zuweisungen sind einzelne Rezepte, kein Gesamtbuild. Später eines wählen; hier keine Plugins geladen.

So funktioniert es

  1. 1Lesen Sie die Karte und verfolgen Sie die deklarierten Werte. Die Seite zeigt Code, führt diese Sprache aber nicht aus.

Grenzfälle und häufige Fehler

  • Ergebnisgrenze

    Die Ergebnisse sind aus dem Quelltext abgeleitet, nicht aufgezeichnete Compiler- oder Laufzeitausgaben. Eingaben, Uhrzeit, Dateien, Threads, externe Dienste und Frameworks bleiben außerhalb der Übungen.

Beispiele

1. 1. Basic ES Module Build verfolgen

Verwendung

Suchen Sie in „Basis-Rollup-Konfiguration“ 1. Basic ES Module Build. Verwenden Sie input=src/index.js und verfolgen Sie nur die genannten Schritte in unveränderter Reihenfolge.

Ergebnis

Erwartet: file=dist/bundle.js; format=es; sourcemap=true. ES-Module und Source Maps sind angefordert, keine geprüften Artefakte.

2. 2. TypeScript Configuration verfolgen

Verwendung

Suchen Sie in „Basis-Rollup-Konfiguration“ 2. TypeScript Configuration. Verwenden Sie input=src/index.ts und verfolgen Sie nur die genannten Schritte in unveränderter Reihenfolge.

Ergebnis

Erwartet: dist/index.esm.js:es; dist/index.cjs.js:cjs. Ein Eingang deklariert zwei Formate und Dateinamen, keinen zweiten Einstieg.

3. 3. Library Configuration: external / globals verfolgen

Verwendung

Suchen Sie in „Basis-Rollup-Konfiguration“ 3. Library Configuration: external / globals. Verwenden Sie external=[lodash,axios] und verfolgen Sie nur die genannten Schritte in unveränderter Reihenfolge.

Ergebnis

Erwartet: UMD globals: lodash→_; axios→axios. Externals bleiben außerhalb; UMD benennt ihre Browser-Globals.

Thema

Tools für Binärbild-Schwellenwerte, Morphologie und Masken

Erzeugen Sie Binärmasken, vergleichen Sie Schwellenwertverfahren, reparieren Sie Vordergrundformen und kombinieren Sie Masken morphologisch und boolesch.

Thema

Audio-Tools für Reverb, Modulation und Sounddesign

Effekte für Reverb, Delay, Modulation und Klangcharakter auswählen, vorhören, vergleichen und für Musik, Video, Podcast und Spiele prüfen.

Thema

JSON-Schema- und API-Vertragsvalidierungs-Tools

Vergleichen Sie JSON-Schema-Validierung, OpenAPI-Response-Prüfung, Mutation Testing, Stress Testing und Breaking-Change-Erkennung in einem Hub für API-Vertragsreviews.

Thema

Gesangs- und Musikuebungs-Tools

Verschiebe Songs in eine bequeme Tonart, finde deinen Stimmumfang, erzeuge Stimmreferenzen, extrahiere Melodie und Akkorde, baue Tempo-Uebungen, fuege Swing hinzu und trainiere Aussprache mit wiederholbaren Browser-Audio-Tools.

Start
Werkzeuge3215
Beispiele593
Visualisierungen472
Dateibetrachter103
Themen239
Schlagwörter333
Bilder, Audio & Video657

Werkzeuge für Bild-, Audio- und Videobearbeitung, Konvertierung und Optimierung

Mathe, Datum & Finanzen647

Rechner, Zahlenwerkzeuge, Datumslogik, Statistik und Finanztools

Design & Farbe298

Werkzeuge für Farben, Layouts, Grafiken, visuelle Gestaltung und Designhilfen

Text & Schreiben209

Werkzeuge für Schreiben, Bereinigung, Formatierung, Extraktion und Textanalyse

Entwicklung & Web194

Entwicklerwerkzeuge, Netzwerk-Utilities, Web-Debugging und Automatisierungshelfer

Konvertierung & Kodierung175

Werkzeuge für Format-, Datei-, Archiv-, Einheiten- und Kodierungskonvertierung

Lead-Quiz veröffentlichen und Kontakte sicher übergeben
Gedenktexte: Familienprüfung und Übergabe zum Druck
Private Gewohnheiten: Sicherung, Wiederherstellung und Freigabeprüfung
Vom Artikel zu X- und LinkedIn-Entwürfen: Faktenprüfung und Übergabe
Interaktive Markdown-Lektion prüfen und offline übergeben

© 2026 Elysia Tools. Alle Rechte vorbehalten.

DokumentationTarifeÜber unsNutzungsbedingungenDatenschutzerklärungCookiesKontakt

Format Conversion

SSH Konfigurations Parser

Analysiert und konvertiert SSH Konfigurationsdateien in JSON Format

Development

Semantischer Konfigurations-Diff

Vergleicht JSON-, YAML-, TOML- und dotenv-Konfigurationen nach Schlüsselpfad und ignoriert Reihenfolge und Formatierungsrauschen.

Development

Visualisierer fuer Umgebungs-Konfigurationsunterschiede

Vergleicht JSON-, YAML-, TOML- und ENV-Konfigurationen zwischen Umgebungen und hebt Drift, fehlende Keys und Bereinigungshinweise hervor.

Format Conversion

Konfigurationsformat-Bridge: TOML / INI / HCL / .env / Nix / dotenv / Kubernetes ConfigMap / Secret

Konvertiert Konfigurationen zwischen dotenv .env, TOML, INI, Java .properties, YAML, JSON, HCL (native Terraform/Vagrant-Syntax) und Nix-Attributmengen und erzeugt Kubernetes-ConfigMap-/Secret-Manifeste; erhält ${VAR}-/{{var}}-Platzhalter und envsubst-Interpolation, verfolgt die Herkunft der Typinferenz (string/int/float/bool/list), faltet HCL-Blocklabels zu verschachtelten Schlüsseln, und ein Round-Trip-Diff hebt nicht-äquivalente Einstellungen hervor (verlorene Schlüssel, Typänderungen, umgeschriebene Werte) — mit Kustomize-Patch-freundlichem YAML.

Format Conversion

WireGuard/OpenVPN-zu-Clash-und-sing-box-Konfigurationsbrücke

Wandelt eingefügten WireGuard- oder OpenVPN-Clienttext in Mihomo/Clash-YAML oder sing-box-JSON um und markiert Geheimfelder; private Schlüssel nicht weitergeben

Development

Docstring-Extraktor

Extrahiert und analysiert Dokumentation aus JavaScript/TypeScript-, Python- und Java-Quellcode

Build-Tools

esbuild Bundler Beispiele

Moderne JavaScript Bundler Beispiele inklusive Konfiguration, Plugins, Optimierung, und Workflow-Integration

Build-Tools

Webpack Konfigurationsbeispiele

Webpack-Konfigurationsbeispiele einschließlich grundlegender Einrichtung, Optimierung, Loadern, Plugins und moderner Webpack-Muster

Build-Tools

Rollup Plugin-Entwicklung

Rollup-Plugin-Entwicklungsbeispiele einschließlich benutzerdefinierter Plugins, Transformationen und Bundling-Patterns

Build-Tools

Vite-Beispiele

Beispiele für das Vite-Build-Tool - Moderner Entwicklungsserver, HMR, Bundling und Plugin-System

Build-Tools

Grunt Build-Tool

Grunt JavaScript Task Runner Beispiele einschließlich Automatisierung, Build-Prozessen und Deployment-Workflows

Build-Tools

Rollup Plugin-Entwicklung

Rollup-Plugin-Entwicklungsbeispiele einschließlich benutzerdefinierter Plugins, Transformationen und Bundling-Patterns