🎯 Рекомендуемые коллекции
Балансированные коллекции примеров кода из различных категорий, которые вы можете исследовать
Примеры конфигурации Rollup
Примеры конфигурации сборочного инструмента Rollup, включая плагины, оптимизацию, многопроектные сборки и современную упаковку JavaScript
⚙️ Базовая конфигурация Rollup
🟢 simple
⭐⭐
Базовая конфигурация Rollup для проектов JavaScript и TypeScript с общими плагинами и оптимизацией
⏱️ 25 min
🏷️ rollup, build-tools, javascript, bundling
Prerequisites:
JavaScript, Node.js, Build tools, Package managers
// 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
export default defineConfig({
input: 'src/index.js',
output: {
file: 'dist/bundle.js',
format: 'es',
sourcemap: true
},
plugins: [
nodeResolve(),
commonjs(),
json()
]
});
// 2. TypeScript Configuration
export default 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
export default 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
export default 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 '@vitejs/plugin-vue';
import { createVuePlugin } from 'rollup-plugin-vue';
export default defineConfig({
input: 'src/main.js',
output: {
file: 'dist/bundle.js',
format: 'es',
sourcemap: true
},
plugins: [
createVuePlugin(),
nodeResolve({
extensions: ['.vue', '.js']
}),
commonjs(),
json()
],
external: ['vue']
});
// 6. Node.js Application
export default 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
export default 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
export default 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';
export default 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';
export default 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';
export default 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';
export default 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';
export default 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').terser()
] : [])
],
watch: {
include: 'src/**'
}
};
});
// 13. Error Handling Configuration
export default 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
export default 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
export default 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
🔴 complex
⭐⭐⭐⭐
Сложные конфигурации Rollup, включая микрофронтенды, monorepo, оптимизацию производительности и интеграцию CI/CD
⏱️ 50 min
🏷️ rollup, advanced, build-tools, architecture
Prerequisites:
Rollup basics, JavaScript/TypeScript, Build tools, CI/CD
// 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
export default 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';
export default 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';
export default 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)
// });
}
};
}
export default 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;
}
}
export default defineConfig([
createConfig('production'),
createConfig('development'),
createConfig('test')
]);
// 7. CI/CD Integration Configuration
import { defineConfig } from 'rollup';
import execute from 'rollup-plugin-execute';
export default 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);
export default 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
export default 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
export default 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/**'
}
})
};
});