Webpack

Modul-Bundler fur JavaScript - Code-Splitting, Loaders, Plugins fur komplexe Build-Pipelines

TL;DR

Was: Ein statischer Modul-Bundler für moderne JavaScript-Anwendungen.

Warum: Assets bündeln, Code transformieren, Builds optimieren, umfangreiches Plugin-Ökosystem.

Quick Start

Installieren:

npm init -y
npm install webpack webpack-cli --save-dev

Dateien erstellen:

src/index.js:

import { greeting } from './greeting.js';
console.log(greeting('World'));

src/greeting.js:

export function greeting(name) {
  return `Hello, ${name}!`;
}

Bauen:

npx webpack

Ausgabe wird in dist/main.js sein

Cheatsheet

BefehlBeschreibung
npx webpackBauen (Produktion)
npx webpack --mode developmentBauen (Entwicklung)
npx webpack serveDev-Server
npx webpack --watchWatch-Modus

Basis-Konfiguration (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