TL;DR
What: A static module bundler for modern JavaScript applications.
Why: Bundle assets, transform code, optimize builds, extensive plugin ecosystem.
Quick Start
Install:
npm init -y
npm install webpack webpack-cli --save-dev
Create files:
src/index.js:
import { greeting } from './greeting.js';
console.log(greeting('World'));
src/greeting.js:
export function greeting(name) {
return `Hello, ${name}!`;
}
Build:
npx webpack
Output will be in dist/main.js
Cheatsheet
| Command | Description |
|---|---|
npx webpack | Build (production) |
npx webpack --mode development | Build (development) |
npx webpack serve | Dev server |
npx webpack --watch | Watch mode |
Basic config (webpack.config.js):
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
mode: 'development',
};
Gotchas
Loaders for non-JS files
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
{
test: /\.(png|jpg|gif)$/,
type: 'asset/resource',
},
],
},
};
Dev server
npm install webpack-dev-server --save-dev
module.exports = {
devServer: {
static: './dist',
hot: true,
port: 3000,
},
};
HTML plugin
npm install html-webpack-plugin --save-dev
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html',
}),
],
};
Next Steps
- Webpack Documentation - Official docs
- Webpack Guides - Step-by-step guides
- Awesome Webpack - Resources
- Consider Vite for faster development