Cheatsheet Webpack
Module bundler para aplicações JavaScript modernas
Webpack
22
cards found
Categories:
Versions:
Settings
Basic Config
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.[contenthash].js',
},
mode: 'production',
};Minimal structure.
Entry and Output
entry: {
app: './src/app.js',
vendor: './src/vendor.js',
},
output: {
filename: '[name].[contenthash].js',
clean: true,
}Multiple entry points.
Resolve and Aliases
resolve: {
extensions: ['.js', '.jsx', '.ts'],
alias: {
'@': path.resolve(__dirname, 'src'),
'components': './src/components',
},
}Module resolution.
Source Maps
devtool: 'source-map' # full
devtool: 'eval-source-map' # fast dev
devtool: 'cheap-module-source-map'
devtool: false # production
Source map options.
Loaders
Rules Structure
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
],
}Define loaders.
Babel (JS/JSX)
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: { presets: ['@babel/preset-env'] }
},
}Transpile JavaScript.
CSS / SASS
// CSS
use: ['style-loader', 'css-loader']
// SASS
use: ['style-loader', 'css-loader',
'sass-loader']
// Extract to file
use: [MiniCssExtractPlugin.loader,
'css-loader']
Process styles.
Assets (Images/Fonts)
{
test: /\.(png|svg|jpg|gif)$/,
type: 'asset',
parser: {
dataUrlCondition: {
maxSize: 8 * 1024
}
}
}Asset modules (Webpack 5).
Plugins
HtmlWebpackPlugin
new HtmlWebpackPlugin({
template: './src/index.html',
title: 'My App',
minify: { collapseWhitespace: true },
})Generate HTML with bundles.
MiniCssExtractPlugin
new MiniCssExtractPlugin({
filename: 'css/[name].[contenthash].css',
})Extract CSS to files.
DefinePlugin
new webpack.DefinePlugin({
'process.env.API_URL':
JSON.stringify(process.env.API_URL),
__DEV__: JSON.stringify(true),
})Compile-time variables.
CopyPlugin and Clean
new CopyPlugin({
patterns: [
{ from: 'public', to: '' }
],
})
output: { clean: true }Copy static assets.
Dev Server
devServer Config
devServer: {
port: 3000,
hot: true,
open: true,
historyApiFallback: true,
proxy: [{
context: ['/api'],
target: 'http://localhost:8080',
}],
}Development server.
HMR (Hot Module)
devServer: { hot: true }
// In the code:
if (module.hot) {
module.hot.accept('./app', () => {
render();
});
}Update without reload.
npm Scripts
"scripts": {
"dev": "webpack serve --mode development",
"build": "webpack --mode production",
"watch": "webpack --watch",
"analyze": "webpack --profile --json > stats.json"
}Run scripts.
Optimization
Code Splitting
optimization: {
splitChunks: {
chunks: 'all',
cacheGroups: {
vendor: {
test: /[\/]node_modules[\/]/,
name: 'vendors',
}
}
}
}Split bundles.
Dynamic Imports
// Lazy loading routes
const Page = React.lazy(
() => import('./pages/Home')
);
// webpackChunkName
import(/* webpackChunkName: "admin" */
'./Admin');
Dynamic import.
Minification
optimization: {
minimize: true,
minimizer: [
new TerserPlugin(),
new CssMinimizerPlugin(),
],
}Minify JS and CSS.
Tree Shaking
// module's package.json:
"sideEffects": false
// or specific:
"sideEffects": ["*.css"]
// mode: 'production' enables it automatically
Remove unused code.
CLI
Basic Commands
npx webpack # build
npx webpack serve # dev server
npx webpack --watch # watch mode
npx webpack --config webpack.prod.js
Run webpack.
Useful Flags
--mode production
--mode development
--entry ./src/main.js
--output-path ./build
--stats verbose
--progress
Command-line options.
Bundle Analysis
npm i -D webpack-bundle-analyzer
new BundleAnalyzerPlugin()
// or:
npx webpack --profile --json > stats.json
npx webpack-bundle-analyzer stats.json
Visualize bundle size.