Elysia Tools

Browse tools, examples, visual explainers, and topic guides from one clear workspace.

Top Categories

Hubs

Language
ZHESPTRUFRDEEN

Elysia Tools

Navigation

Build Tools

Rollup outputs, module formats and external globals | Elysia Tools

Work through three bounded Rollup examples with explicit inputs and independently checkable outcomes.

Samples

Entries inside this sample collection

ConfigSimple

Basic Rollup Configuration

Essential Rollup configuration for JavaScript and TypeScript projects with common plugins and optimizations

Difficulty

4/10

Estimated time

25 min

Tags

rollup, build-tools, javascript, bundling

Prerequisites

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

Advanced Rollup Configuration

Complex Rollup configurations including microfrontends, monorepos, performance optimization, and CI/CD integration

Difficulty

8/10

Estimated time

50 min

Tags

rollup, advanced, build-tools, architecture

Prerequisites

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

Tools

Tools frequently paired with this sample

Related

Related sample collections

Related

Related workflows

Tool usage guide

Sample-focused context for search and workflow understanding

Overview

Use Basic Rollup Configuration for the exercises below. Follow only the named block; the other cards introduce separate language features and dependencies.

Choose the smallest example

Read the named configuration or expression without importing it. All inputs below are hypothetical literals; no build command, hook, package installation or file operation is needed.

The repeated rollupConfig assignments are separate recipes, not a combined build. Choose one recipe before any future project use; no plugin has been imported or called here.

How it works

  1. 1Read the named card and trace the declared values. The sample page displays code; it does not execute this language for you.

Edge cases & common failures

  • Scope of the result

    Results below are source-derived expectations, not recorded compiler or runtime output. Interactive input, time, files, threads, external services and framework setup are outside these exercises.

Examples

1. Trace 1. Basic ES Module Build

How to use

In Basic Rollup Configuration, locate 1. Basic ES Module Build. Use input=src/index.js; follow only the stated operations, preserving their order.

Outcome

Expected: file=dist/bundle.js; format=es; sourcemap=true. The output format is ES modules and source maps are requested, not verified artifacts.

2. Trace 2. TypeScript Configuration

How to use

In Basic Rollup Configuration, locate 2. TypeScript Configuration. Use input=src/index.ts; follow only the stated operations, preserving their order.

Outcome

Expected: dist/index.esm.js:es; dist/index.cjs.js:cjs. One input declares two output formats with distinct filenames; no second entry is implied.

3. Trace 3. Library Configuration: external / globals

How to use

In Basic Rollup Configuration, locate 3. Library Configuration: external / globals. Use external=[lodash,axios]; follow only the stated operations, preserving their order.

Outcome

Expected: UMD globals: lodash→_; axios→axios. External dependencies stay outside the bundle; the UMD configuration names their browser globals.

Hub

Infer JSON Schema from Samples and Spreadsheets

Derive a reviewable JSON Schema draft from representative JSON samples or XLSX rows, then inspect types, requiredness, nulls, and outliers before treating it as a contract.

Hub

Singing and Music Practice Tools

Shift songs into a comfortable key, find vocal range, generate tuning references, extract melody and chords, build tempo drills, add swing, and practice pronunciation with repeatable browser audio tools.

Hub

Environment and Configuration Format Workflow

Inspect, validate, convert, merge, and diff configuration without exposing secrets or losing the source of truth.

Hub

JSON Schema and API Contract Validation Tools

Compare JSON schema validation, OpenAPI response checks, mutation testing, stress testing, and breaking-change detection tools in one hub for API contract review.

Home
Tools3215
Samples593
Visualizations472
Viewers103
Hubs239
Tags333
Images, Audio & Video657

Image, audio, and video processing, conversion, and optimization tools

Math, Date & Finance647

Calculators, numerics, date logic, statistics, and finance tools

Design & Color298

Color, layout, graphics, visual styling, and design helper tools

Text & Writing209

Writing, cleanup, formatting, extraction, and text analysis tools

Developer & Web194

Developer utilities, networking, web debugging, and automation helpers

Conversion & Encoding175

Format, file, archive, unit, and encoding conversion tools

Lead Generation Quiz Launch and Contact Handoff
Memorial Drafts: Family Review and Print Handoff
Private Habit Records: Backup, Restore and Sharing Review
Article to X and LinkedIn Drafts: Fact Review and Handoff
Markdown Interactive Deck Review and Offline Handoff

© 2026 Elysia Tools. All rights reserved.

DocsPricingAboutTerms of ServicePrivacy PolicyCookiesContact

Format Conversion

SSH Config Parser

Parse and convert SSH configuration file to JSON format

Development

Config File Semantic Diff

Compare JSON, YAML, TOML, and dotenv configurations by key path while ignoring ordering and formatting noise.

Development

Environment Config Diff Visualizer

Compare dev, staging, and production configuration bundles across JSON, YAML, TOML, or ENV formats and highlight drift, missing keys, and cleanup suggestions

Format Conversion

TOML / INI / HCL / .env / Nix / dotenv ⇄ Kubernetes ConfigMap & Secret Config Format Bridge

Convert configuration files between dotenv .env, TOML, INI, Java .properties, YAML, JSON, HCL (Terraform/Vagrant native syntax) and Nix attribute sets, and emit Kubernetes ConfigMap or Secret manifests. Template placeholders (${VAR}, {{var}}, envsubst) are preserved verbatim, type inference provenance (string/int/float/bool/list) is tracked, HCL block labels fold into nested keys, and a round-trip diff calls out non-equivalent settings — dropped keys, re-typed values and rewrites — instead of coercing them silently.

Format Conversion

WireGuard/OpenVPN to Clash and sing-box Config Bridge

Convert pasted WireGuard or OpenVPN client text into Mihomo/Clash YAML or sing-box JSON with secret-field diagnostics; do not share private keys

Development

Docstring Extractor

Extract and parse documentation from JavaScript/TypeScript, Python, and Java source code

Build Tools

esbuild Bundler Samples

Modern JavaScript bundler examples including configuration, plugins, optimization, and integration workflows

Build Tools

Webpack Configuration Samples

Webpack configuration examples including basic setup, optimization, loaders, plugins, and modern webpack patterns

Build Tools

Rollup Plugins Development

Rollup plugin development examples including custom plugins, transforms, and bundling patterns

Build Tools

Vite Examples

Vite build tool examples - Modern development server, HMR, bundling, and plugin system

Build Tools

Grunt Build Tool

Grunt JavaScript task runner examples including automation, build processes, and deployment workflows

Build Tools

Gulp Task Automation

Gulp task runner examples including build automation, file processing, and development workflows