| name | webpack-config |
| description | Webpack 5 configuration — loaders, plugins, code splitting, tree shaking, module federation, dev server. Use when working with webpack config. |
| domain | development |
| author | oyi77 |
| license | Apache-2.0 |
| subdomain | software-development |
| tags | ["coding","config","software-engineering","testing","webpack"] |
| version | 1.0.0 |
Overview
Webpack 5 is a static module bundler for modern JavaScript applications. It processes every module in your project, applies loaders and plugins, and outputs optimized bundles. This skill covers configuration patterns for production-grade builds.
Capabilities
- Bundle JS/TS/CSS/assets into optimized output files
- Code splitting with dynamic imports and splitChunks
- Tree shaking to eliminate dead code
- Module Federation for micro-frontends
- Hot Module Replacement (HMR) for development
- Asset processing with loaders (images, fonts, CSS, etc.)
- Environment-specific configuration (dev/prod)
- Source maps for debugging
- Bundle analysis and optimization
When to Use
Trigger phrases:
-
"webpack config"
-
"Webpack 5 configuration — loaders, plugins, code splitting, tree shaking, module"
-
Building complex web applications with many dependencies
-
Need fine-grained control over bundling
-
Implementing micro-frontends with Module Federation
-
Migrating legacy projects to modern bundling
-
Need custom loader/plugin pipeline
-
Building library packages
When NOT to Use
- Task is about deployment, not development (use deploy skills)
- Task is about code review, not writing (use review skills)
- You need to understand existing code first (use research skills)
- Task is about testing only (use test skills)
- Requirements are unclear (clarify first)
- Task is trivially simple (single line fix)
Pseudo Code
The webpack-config workflow follows a standard pipeline pattern.
Core flow:
# webpack-config primary flow
input = prepare(raw_data)
result = process(input, config={code, config, configuration, federation, loaders})
validate(result)
deliver(result)
Error handling:
on error:
log(error_details)
retry_with_backoff(max=3)
if still_failing: alert_and_escalate()
Basic Configuration
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
module.exports = (env, argv) => {
const isProd = argv.mode === 'production';
return {
entry: './src/index.tsx',
output: {
path: path.resolve(__dirname, 'dist'),
filename: isProd ? '[name].[contenthash:8].js' : '[name].js',
clean: true,
publicPath: '/',
},
resolve: {
extensions: ['.tsx', '.ts', '.js', '.jsx'],
alias: {
'@': path.resolve(__dirname, 'src'),
},
},
module: {
rules: [
{
test: /\.[jt]sx?$/,
: ,
: ,
},
{
: ,
: [
isProd ? . : ,
,
,
],
},
{
: ,
: ,
: { : { : * } },
},
{
: ,
: ,
},
],
},
: [
({ : }),
isProd && ({ : }),
].(),
: {
: [, ()],
: {
: ,
: {
: { : , : , : },
},
},
},
: {
: ,
: ,
: ,
: { : },
},
: isProd ? : ,
};
};
Code Splitting (Dynamic Imports)
const Dashboard = React.lazy(() => import('./pages/Dashboard'));
const Settings = React.lazy(() => import('./pages/Settings'));
function App() {
return (
<Suspense fallback={<Loading />}>
<Routes>
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/settings" element={<Settings />} />
</Routes>
</Suspense>
);
}
Module Federation
const { ModuleFederationPlugin } = require('webpack').container;
new ModuleFederationPlugin({
name: 'host',
remotes: {
remoteApp: 'remoteApp@http://localhost:3001/remoteEntry.js',
},
shared: { react: { singleton: true }, 'react-dom': { singleton: true } },
});
new ModuleFederationPlugin({
name: 'remoteApp',
filename: 'remoteEntry.js',
exposes: { './Widget': './src/Widget' },
shared: { react: { singleton: true }, 'react-dom': { singleton: true } },
});
const RemoteWidget = React.lazy(() => import('remoteApp/Widget'));
Bundle Analysis
npm install --save-dev webpack-bundle-analyzer
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
plugins: [new BundleAnalyzerPlugin()]
npx webpack --mode production --stats-error-details
Error Handling
| Error | Cause | Fix |
|---|
Module not found | Missing import or alias | Check resolve.extensions and resolve.alias |
Out of memory | Bundle too large | Increase NODE_OPTIONS=--max-old-space-size=4096 |
HMR not working | Dev server misconfig | Check devServer.hot: true and entry point |
CSS not loading | Missing loader | Add style-loader + css-loader |
Tree shaking not working | CommonJS modules | Use ESM (import/export syntax), check sideEffects |
Common Patterns
Proven patterns for webpack-config usage.
- Batch processing: Process multiple items in parallel for throughput
- Retry with backoff: Handle transient failures gracefully
- Rate limiting: Respect API limits with configurable delays
- Logging: Structured logging for debugging and audit trails
Environment Config
const Dotenv = require('dotenv-webpack');
module.exports = (env) => ({
plugins: [
new Dotenv({ path: env.production ? '.env.production' : '.env.development' }),
],
});
TypeScript Config
module.exports = {
module: {
rules: [{ test: /\.tsx?$/, use: 'ts-loader', exclude: /node_modules/ }],
},
};
SVG as React Components
module.exports = {
module: {
rules: [
{
test: /\.svg$/,
use: ['@svgr/webpack', 'url-loader'],
},
],
},
};
Performance Budgets
module.exports = {
performance: {
maxAssetSize: 250000,
maxEntrypointSize: 250000,
hints: 'warning',
},
};
How to Use
- Understand the requirement and existing codebase patterns
- Design the solution with error handling and testability in mind
- Implement incrementally with tests for each change
- Verify against expected outcomes (manual and automated)
- Document usage, edge cases, and integration points
- Review with team before merging to shared branches
Red Flags
- Skipping tests to ship faster: Untested code breaks in production when you least expect it
- No error handling in production code: Unhandled errors crash services and lose user data
- Hardcoded configuration values: Hardcoded values prevent environment switching and leak secrets
- Ignoring security implications: Missing input validation, auth bypasses, and injection vulnerabilities
- Over-engineering simple solutions: Premature abstraction adds complexity without proportional benefit
Verification
Process
- Analyze the task requirements
- Apply domain expertise
- Verify output quality
Anti-Rationalization Table
| Rationalization | Reality |
|---|
| "Tests slow me down" | Bugs slow you down 10x more. Tests are speed, not overhead. |
| "I will refactor later" | Technical debt compounds. Refactor as you go. |
| "It works on my machine" | If it is not in CI, it does not work. Ship proof, not claims. |