Gebruikershandleiding
Deze handleiding behandelt de kernfunctionaliteit van webpack, inclusief configuratieopties, CLI-gebruik en best practices voor zowel Webpack 4 als Webpack 5.
Configuratie
Webpack wordt standaard geconfigureerd via een JavaScript-bestand met de naam webpack.config.js. Dit bestand exporteert een configuratieobject dat aangeeft hoe webpack uw project moet bouwen.
Basisconfiguratie
// Webpack 4 / Webpack 5 (CommonJS)
const path = require('path');
module.exports = {
mode: 'production',
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
};
// Webpack 5 (ES Modules)
import path from 'node:path';
export default {
mode: 'production',
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(import.meta.dirname, 'dist'),
},
};
Configuratietypes
Webpack ondersteunt meerdere typen configuratiebestanden:
| Type | Webpack 4 | Webpack 5 | Beschrijving |
|---|---|---|---|
| CommonJS | ✅ | ✅ | module.exports = {} |
| ES-modules | ⚠️ Beperkt | ✅ Volledig | export default {} |
| TypeScript | ⚠️ Met ts-node | ✅ Ingebouwd | .ts-bestanden |
| Meerdere configuraties | ✅ | ✅ | Array van configuraties |
Entry points
Het entrypoint vertelt webpack waar het moet beginnen met het opbouwen van de afhankelijkheidsgrafiek.
Enkel entrypoint
// Webpack 4 & 5
module.exports = {
entry: './src/index.js',
};
Meerdere entrypoints
// Webpack 4 & 5
module.exports = {
entry: {
main: './src/index.js',
vendor: './src/vendor.js',
},
};
Dynamische entrypoints
// Webpack 4 & 5
module.exports = {
entry: {
page1: './src/page1.js',
page2: './src/page2.js',
},
};
Entry-object met arrays
// Webpack 4 & 5
module.exports = {
entry: {
app: ['./src/index.js', './src/another.js'],
},
};
Output
De outputconfiguratie vertelt webpack waar het de bundels die het maakt moet uitvoeren.
Basisoutput
// Webpack 4 & 5
module.exports = {
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
};
Benoemde output met [name]
// Webpack 4 & 5
module.exports = {
entry: {
main: './src/index.js',
another: './src/another.js',
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
},
};
Output met [hash] en [chunkhash]
// Webpack 4 & 5
module.exports = {
output: {
filename: '[name].[contenthash].js',
path: path.resolve(__dirname, 'dist'),
clean: true, // Webpack 5 only - cleans dist folder
},
};
Configuratievergelijking
| Functie | Webpack 4 | Webpack 5 |
|---|---|---|
| Output.clean | ❌ Niet beschikbaar | ✅ Map dist automatisch opschonen |
| Output.pathinfo | ✅ Standaard true | ✅ Standaard false (productie) |
| Output.hashFunction | MD4 | MD4 (standaard), md4, xxHash64, bubblehash |
| Output.module | ❌ Niet beschikbaar | ✅ Uitvoer als ES-module |
| Output.environment | ❌ Niet beschikbaar | ✅ Instellingen voor ES-moduleondersteuning |
Loaders
Loaders stellen webpack in staat om meer dan alleen JavaScript-bestanden te verwerken.
Basisconfiguratie van loaders
// Webpack 4 & 5
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
{
test: /\.js$/,
exclude: /node_modules/,
use: 'babel-loader',
},
],
},
};
Loaderopties
// Webpack 4 & 5
module.exports = {
module: {
rules: [
{
test: /\.js$/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env'],
plugins: ['@babel/plugin-transform-runtime'],
},
},
},
],
},
};
Asset Modules (alleen Webpack 5)
Webpack 5 introduceerde Asset Modules als vervanging voor file-loader, url-loader en raw-loader.
// Webpack 5
module.exports = {
module: {
rules: [
// replaced file-loader
{
test: /\.(png|jpg|gif)$/,
type: 'asset/resource',
},
// replaced url-loader
{
test: /\.svg$/,
type: 'asset',
parser: {
dataUrlCondition: {
maxSize: 8 * 1024, // 8kb
},
},
},
// replaced raw-loader
{
test: /\.txt$/,
type: 'asset/source',
},
],
},
};
Loadervergelijking
| Loader-type | Webpack 4 | Webpack 5 | Vervangend module |
|---|---|---|---|
| file-loader | Vereist | ✅ Alternatief | asset/resource |
| url-loader | Vereist | ✅ Alternatief | asset |
| raw-loader | Vereist | ✅ Alternatief | asset/source |
| svg-url-loader | Vereist | ✅ Alternatief | Aangepaste verwerking |
Plug-ins
Plug-ins voeren een breder scala aan taken uit dan loaders, van optimalisatie van bundels tot injectie van omgevingsvariabelen.
Basisconfiguratie van plug-ins
// Webpack 4 & 5
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
module.exports = {
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html',
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production'),
}),
],
};
Gangbare plug-ins
| Plug-in | Beschrijving | Webpack 4 | Webpack 5 |
|---|---|---|---|
| html-webpack-plugin | Genereert HTML-bestanden | ✅ | ✅ |
| mini-css-extract-plugin | Extraheert CSS naar aparte bestanden | ✅ | ✅ |
| clean-webpack-plugin | Maakt de uitvoermap schoon | ✅ | ✅ |
| terser-webpack-plugin | Minimaliseert JavaScript | ✅ | ✅ |
| filemanager-webpack-plugin | Bestandssysteemhandelingen | ✅ | ✅ |
| module-federation-plugin | Module Federation | ❌ | ✅ |
Ingebouwde plug-ins van Webpack 5
Webpack 5 bevat verschillende plug-ins die in Webpack 4 extern waren:
| Plug-in | Webpack 4 | Webpack 5 |
|---|---|---|
| asset-plugins | Vereist | ✅ Ingebouwd |
| module-federation | Vereist | ✅ Ingebouwd |
| persistent-cache | Vereist | ✅ Ingebouwd |
Mode
Webpack biedt drie ingebouwde mode-opties: development, production en none.
// Webpack 4 & 5
module.exports = {
mode: 'development', // or 'production' or 'none'
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
};
Modespecifieke optimalisaties
| Optimalisatie | development | production |
|---|---|---|
| nodeEnv | 'development' | 'production' |
| debug | true | false |
| moduleIds | 'named' | 'deterministic' |
| chunkIds | 'named' | 'deterministic' |
| optimization.removeAvailableModules | false | true |
| optimization.removeEmptyChunks | false | true |
| optimization.splitChunks | false | true |
| optimization.minimize | false | true |
Ontwikkeltools
Source Maps
Source maps helpen bij het debuggen van gecompileerde code door deze terug te koppelen aan de oorspronkelijke broncode.
| Optie | Webpack 4 | Webpack 5 | Beschrijving |
|---|---|---|---|
eval | ✅ | ✅ | Snelste, verpakt in eval() |
cheap-eval-source-map | ✅ | ✅ | Goed voor ontwikkeling |
cheap-module-eval-source-map | ✅ | ✅ | Behoudt de oorspronkelijke broncode |
source-map | ✅ | ✅ | Beste kwaliteit, langzaamst |
hidden-source-map | ✅ | ✅ | Wordt niet in de bundel genoemd |
eval-source-map | ✅ | ✅ | Werkt met eval() |
Webpack Dev Server
Webpack Dev Server biedt een ontwikkelserver met live herlading.
// Webpack 4 & 5
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
devServer: {
static: {
directory: path.join(__dirname, 'public'),
},
port: 9000,
hot: true,
},
};
Configuratievergelijking
| Functie | Webpack 4 | Webpack 5 |
|---|---|---|
| devServer.static | map als string | object met de eigenschap directory |
| devServer.contentBase | ✅ Verouderd | ❌ Verwijderd |
| watchOptions | Directe eigenschap | Directe eigenschap |
| server | ❌ Niet beschikbaar | ✅ Nieuwe serverconfiguratie |
Codesplitsing
Webpack kan uw code opsplitsen in meerdere bundels voor betere prestaties.
Dynamische imports (Webpack 4 & 5)
// Webpack 4 & 5
button.addEventListener('click', () => {
import('./module').then((module) => {
module.default();
});
});
Magische commentaren (Webpack 4 & 5)
// Webpack 4 & 5
import(
/* webpackChunkName: "my-chunk" */
/* webpackMode: "lazy" */
'./module'
).then((module) => {
module.default();
});
SplitChunks-configuratie
// Webpack 4 & 5
module.exports = {
optimization: {
splitChunks: {
chunks: 'all',
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all',
},
},
},
},
};
Configuratievergelijking
| Functie | Webpack 4 | Webpack 5 |
|---|---|---|
| optimization.splitChunks.cacheGroups | ✅ | ✅ |
| optimization.chunkGroups | ❌ Niet beschikbaar | ✅ Beschikbaar |
| optimization.moduleConcatenation | ✅ (Optimization.concatenateModules) | ✅ (Optimization.concatenateModules) |
| fetchPriority | ❌ Niet beschikbaar | ✅ Beschikbaar voor import() |
Module Federation (alleen Webpack 5)
Module Federation is een nieuwe functie in Webpack 5 waarmee code tussen verschillende builds op runtime kan worden gedeeld.
Hostconfiguratie
// Webpack 5 - Host application
const ModuleFederationPlugin = require('webpack').container
.ModuleFederationPlugin;
module.exports = {
plugins: [
new ModuleFederationPlugin({
name: 'host',
filename: 'remoteEntry.js',
exposes: {
'./Button': './src/Button',
},
remotes: {
remote: 'remote@http://localhost:3002/remoteEntry.js',
},
shared: ['react', 'react-dom'],
}),
],
};
Remoteconfiguratie
// Webpack 5 - Remote application
const ModuleFederationPlugin = require('webpack').container
.ModuleFederationPlugin;
module.exports = {
plugins: [
new ModuleFederationPlugin({
name: 'remote',
filename: 'remoteEntry.js',
exposes: {
'./Button': './src/Button',
},
shared: ['react', 'react-dom'],
}),
],
};
Deze functie is niet beschikbaar in Webpack 4 en vereist plug-ins van derden voor vergelijkbare functionaliteit.
Prestaties
Webpack biedt verschillende opties om de bouwprestaties te verbeteren.
Prestatiehints
// Webpack 4 & 5
module.exports = {
performance: {
hints: 'warning', // or 'error' or false
maxAssetSize: 200000,
maxEntrypointSize: 400000,
},
};
Cacheconfiguratie
// Webpack 4 - requiring external plugin
const FileSystemCache = require('fs-cache');
// Webpack 5 - built-in
module.exports = {
cache: {
type: 'filesystem', // new in Webpack 5
cacheDirectory: path.resolve(__dirname, '.webpack_cache'),
},
};
Configuratievergelijking
| Functie | Webpack 4 | Webpack 5 |
|---|---|---|
| cache.type | ❌ Niet beschikbaar | ✅ 'memory' of 'filesystem' |
| buildDependencies | ❌ Niet beschikbaar | ✅ Wijzigingen in het configuratiebestand volgen |
| managedPaths | ❌ Niet beschikbaar | ✅ Caching optimaliseren op macOS/Linux |
CLI-referentie
Basiscommando's
| Commando | Beschrijving |
|---|---|
webpack | Webpack build uitvoeren |
webpack build | Webpack build uitvoeren (expliciet) |
webpack watch | Letten op bestandswijzigingen |
webpack serve | webpack-dev-server uitvoeren |
webpack info | Systeeminformatie weergeven |
webpack configtest | Webpack-configuratie valideren |
Gangbare vlaggen
| Vlag | Beschrijving |
|---|---|
--mode development | Mode instellen op development |
--mode production | Mode instellen op production |
--config webpack.config.js | Eigen configuratiebestand gebruiken |
--entry ./src/index.js | Entrypoint instellen |
-o, --output-path ./dist | Uitvoermap instellen |
-w, --watch | Letten op wijzigingen |
--devtool source-map | Optie voor source maps instellen |
--json | Statistieken als JSON afdrukken |
--progress | Voortgang van de compilatie tonen |
Configuratievergelijking
| Functie | Webpack 4 | Webpack 5 |
|---|---|---|
| --env | Alleen stringwaarden | Objectwaarden ondersteund |
| --config-node-env | ❌ Niet beschikbaar | ✅ process.env.NODE_ENV instellen |
| --analyze | Vereist plug-in | ✅ Ingebouwde ondersteuning |
| --info | Basisuitvoer | Uitgebreide uitvoer |
Omgevingsvariabelen
Webpack biedt verschillende ingebouwde omgevingsvariabelen:
| Variabele | Beschrijving |
|---|---|
WEBPACK_SERVE | true als webpack-dev-server wordt gebruikt |
WEBPACK_BUILD | true als er wordt gebouwd |
WEBPACK_WATCH | true als er wordt gekeken naar wijzigingen |
Gebruiksexample
// Webpack 4 & 5
module.exports = (env, argv) => {
return {
mode: argv.mode || 'development',
devServer: argv.WEBPACK_SERVE ? {
static: './dist',
} : undefined,
};
};
Best practices
Organisatie van de configuratie
// Webpack 4 & 5 - Base configuration
const path = require('path');
module.exports = (env, argv) => {
const isProduction = argv.mode === 'production';
return {
mode: argv.mode || 'development',
entry: './src/index.js',
output: {
filename: isProduction ? '[name].[contenthash].js' : '[name].js',
path: path.resolve(__dirname, 'dist'),
clean: isProduction, // Webpack 5 only
},
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
],
},
plugins: [
// Production-only plugins
...(isProduction ? [] : []),
],
optimization: {
minimize: isProduction,
},
};
};
Versiespecifieke best practices
Webpack 4
- Gebruik
file-loaderenurl-loadervoor assets - Configureer caching met
cache-loader - Gebruik
optimization.concatenateModulesvoor scope hoisting - Gebruik
ExtractTextPluginvoor het extraheren van CSS
Webpack 5
- Gebruik Asset Modules in plaats van file-loader/url-loader
- Schakel
cache.type = 'filesystem'in voor snellere herbouwen - Gebruik de ingebouwde Module Federation voor micro-frontends
- Gebruik
_magic_commentsvoor optimalisatie van import()
Migratie van Webpack 4 naar Webpack 5
Stap 1: Werk Node.js bij
Webpack 5 vereist Node.js 10.13.0 of later:
# Check your version
node -v
# Update if needed
nvm install 14
nvm use 14
Stap 2: Vervang loaders door Asset Modules
Webpack 4:
{
test: /\.(png|jpg|gif)$/,
use: 'file-loader'
}
Webpack 5:
{
test: /\.(png|jpg|gif)$/,
type: 'asset/resource'
}
Stap 3: Schakel duurzame caching in
Webpack 4: Vereist een externe plug-in Webpack 5: Ingebouwd
cache: {
type: 'filesystem',
},
Stap 4: Werk de CSS-extractie bij
Webpack 4:
npm install extract-text-webpack-plugin --save-dev
Webpack 5:
npm install mini-css-extract-plugin --save-dev
Stap 5: Werk het plug-in-gebruik bij
Sommige plug-ins zijn in Webpack 5 vervangen of bijgewerkt. Controleer de plug-indocumentatie op compatibiliteit.
