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:

TypeWebpack 4Webpack 5Beschrijving
CommonJS✅✅module.exports = {}
ES-modules⚠️ Beperkt✅ Volledigexport 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

FunctieWebpack 4Webpack 5
Output.clean❌ Niet beschikbaar✅ Map dist automatisch opschonen
Output.pathinfo✅ Standaard true✅ Standaard false (productie)
Output.hashFunctionMD4MD4 (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-typeWebpack 4Webpack 5Vervangend module
file-loaderVereist✅ Alternatiefasset/resource
url-loaderVereist✅ Alternatiefasset
raw-loaderVereist✅ Alternatiefasset/source
svg-url-loaderVereist✅ AlternatiefAangepaste 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-inBeschrijvingWebpack 4Webpack 5
html-webpack-pluginGenereert HTML-bestanden✅✅
mini-css-extract-pluginExtraheert CSS naar aparte bestanden✅✅
clean-webpack-pluginMaakt de uitvoermap schoon✅✅
terser-webpack-pluginMinimaliseert JavaScript✅✅
filemanager-webpack-pluginBestandssysteemhandelingen✅✅
module-federation-pluginModule Federation❌✅

Ingebouwde plug-ins van Webpack 5

Webpack 5 bevat verschillende plug-ins die in Webpack 4 extern waren:

Plug-inWebpack 4Webpack 5
asset-pluginsVereist✅ Ingebouwd
module-federationVereist✅ Ingebouwd
persistent-cacheVereist✅ 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

Optimalisatiedevelopmentproduction
nodeEnv'development''production'
debugtruefalse
moduleIds'named''deterministic'
chunkIds'named''deterministic'
optimization.removeAvailableModulesfalsetrue
optimization.removeEmptyChunksfalsetrue
optimization.splitChunksfalsetrue
optimization.minimizefalsetrue

Ontwikkeltools

Source Maps

Source maps helpen bij het debuggen van gecompileerde code door deze terug te koppelen aan de oorspronkelijke broncode.

OptieWebpack 4Webpack 5Beschrijving
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

FunctieWebpack 4Webpack 5
devServer.staticmap als stringobject met de eigenschap directory
devServer.contentBase✅ Verouderd❌ Verwijderd
watchOptionsDirecte eigenschapDirecte 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

FunctieWebpack 4Webpack 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

FunctieWebpack 4Webpack 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

CommandoBeschrijving
webpackWebpack build uitvoeren
webpack buildWebpack build uitvoeren (expliciet)
webpack watchLetten op bestandswijzigingen
webpack servewebpack-dev-server uitvoeren
webpack infoSysteeminformatie weergeven
webpack configtestWebpack-configuratie valideren

Gangbare vlaggen

VlagBeschrijving
--mode developmentMode instellen op development
--mode productionMode instellen op production
--config webpack.config.jsEigen configuratiebestand gebruiken
--entry ./src/index.jsEntrypoint instellen
-o, --output-path ./distUitvoermap instellen
-w, --watchLetten op wijzigingen
--devtool source-mapOptie voor source maps instellen
--jsonStatistieken als JSON afdrukken
--progressVoortgang van de compilatie tonen

Configuratievergelijking

FunctieWebpack 4Webpack 5
--envAlleen stringwaardenObjectwaarden ondersteund
--config-node-env❌ Niet beschikbaar✅ process.env.NODE_ENV instellen
--analyzeVereist plug-in✅ Ingebouwde ondersteuning
--infoBasisuitvoerUitgebreide uitvoer

Omgevingsvariabelen

Webpack biedt verschillende ingebouwde omgevingsvariabelen:

VariabeleBeschrijving
WEBPACK_SERVEtrue als webpack-dev-server wordt gebruikt
WEBPACK_BUILDtrue als er wordt gebouwd
WEBPACK_WATCHtrue 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

  1. Gebruik file-loader en url-loader voor assets
  2. Configureer caching met cache-loader
  3. Gebruik optimization.concatenateModules voor scope hoisting
  4. Gebruik ExtractTextPlugin voor het extraheren van CSS

Webpack 5

  1. Gebruik Asset Modules in plaats van file-loader/url-loader
  2. Schakel cache.type = 'filesystem' in voor snellere herbouwen
  3. Gebruik de ingebouwde Module Federation voor micro-frontends
  4. Gebruik _magic_comments voor 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.