Webpack Cheatsheet¶
Webpack - Static Module Bundler
Webpack ist ein statischer Modulbündelr für moderne JavaScript-Anwendungen. Wenn Webpack Ihre Anwendung verarbeitet, baut es intern ein Abhängigkeitsdiagramm aus einem oder mehreren Eingabepunkten und kombiniert dann jedes Modul, das Ihr Projekt benötigt, in ein oder mehrere Pakete. < p>
Inhaltsverzeichnis¶
- [Installation](#installation
- Basic Configuration
- (Entry Points)(LINK_2__)
- [Ausgabe](#output_
- (Loaders) (#loaders)
- (Plugins)(LINK_5_)
- (Mode)(LINK_6__)
- [Entwicklungsserver](#development-server
- [Code Splitting](#code-splitting_
- Optimierung
- [Modul-Resolution](#module-resolution
- (#hot-module-replacement_)
- Umweltvariablen
- (#production-build_)
- Erweiterte Konfiguration
- Performance
- (#troubleshooting_)
- Beste Praktiken
Installation¶
Globale Installation¶
# Install webpack globally
npm install -g webpack webpack-cli
# Check version
webpack --version
```_
### Lokale Installation (empfohlen)
```bash
# Initialize npm project
npm init -y
# Install webpack locally
npm install --save-dev webpack webpack-cli
# Install webpack dev server
npm install --save-dev webpack-dev-server
# Install common loaders and plugins
npm install --save-dev html-webpack-plugin css-loader style-loader file-loader url-loader
```_
### Paket.json Scripts
```json
{
"scripts": {
"build": "webpack --mode production",
"dev": "webpack --mode development",
"start": "webpack serve --mode development",
"watch": "webpack --mode development --watch"
}
}
```_
## Grundkonfiguration
### Minimal webpack.config.js
```javascript
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
```_
### Vollständige grundlegende Konfiguration
```javascript
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.[contenthash].js',
path: path.resolve(__dirname, 'dist'),
clean: true
},
module: {
rules: [
{
test: /\.css$/i,
use: ['style-loader', 'css-loader']
},
{
test: /\.(png|svg|jpg|jpeg|gif)$/i,
type: 'asset/resource'
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html'
})
]
};
```_
### TypScript Konfiguration
```javascript
const path = require('path');
module.exports = {
entry: './src/index.ts',
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
resolve: {
extensions: ['.tsx', '.ts', '.js']
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
```_
## Eintrittspunkte
### Single Entry Point
```javascript
module.exports = {
entry: './src/index.js'
};
```_
### Mehrere Entry Points
```javascript
module.exports = {
entry: {
main: './src/index.js',
vendor: './src/vendor.js'
}
};
```_
### Dynamische Eingangspunkte
```javascript
module.exports = {
entry: () => {
return {
main: './src/index.js',
admin: './src/admin.js'
};
}
};
```_
### Eintritt mit Abhängigkeiten
```javascript
module.exports = {
entry: {
main: {
import: './src/index.js',
dependOn: 'shared'
},
admin: {
import: './src/admin.js',
dependOn: 'shared'
},
shared: 'lodash'
}
};
```_
## Ausgabe
### Grundlegende Ausgangskonfiguration
```javascript
const path = require('path');
module.exports = {
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
```_
### Mehrfacher Eingang Ausgang
```javascript
module.exports = {
entry: {
main: './src/index.js',
admin: './src/admin.js'
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
```_
### Ausgabe mit Hashing
```javascript
module.exports = {
output: {
filename: '[name].[contenthash].js',
path: path.resolve(__dirname, 'dist'),
clean: true
}
};
```_
### Public Path Konfiguration
```javascript
module.exports = {
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/assets/'
}
};
```_
### Bibliothek Ausgabe
```javascript
module.exports = {
output: {
filename: 'my-library.js',
path: path.resolve(__dirname, 'dist'),
library: {
name: 'MyLibrary',
type: 'umd'
}
}
};
```_
## Lastkraftwagen
### CSS Lastkraftwagen
```javascript
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: ['style-loader', 'css-loader']
},
{
test: /\.s[ac]ss$/i,
use: ['style-loader', 'css-loader', 'sass-loader']
},
{
test: /\.less$/i,
use: ['style-loader', 'css-loader', 'less-loader']
}
]
}
};
```_
### JavaScript Loading
```javascript
module.exports = {
module: {
rules: [
{
test: /\.m?js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
}
},
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
}
};
```_
### Die Datei wird geladen
```javascript
module.exports = {
module: {
rules: [
{
test: /\.(png|svg|jpg|jpeg|gif)$/i,
type: 'asset/resource'
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/i,
type: 'asset/resource'
},
{
test: /\.(csv|tsv)$/i,
use: ['csv-loader']
},
{
test: /\.xml$/i,
use: ['xml-loader']
}
]
}
};
```_
### Anlagemodule
```javascript
module.exports = {
module: {
rules: [
{
test: /\.png/,
type: 'asset/resource'
},
{
test: /\.html/,
type: 'asset/resource'
},
{
test: /\.txt/,
type: 'asset/source'
},
{
test: /\.jpg/,
type: 'asset',
parser: {
dataUrlCondition: {
maxSize: 4 * 1024 // 4kb
}
}
}
]
}
};
```_
### Ladeoptionen
```javascript
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: true,
sourceMap: true
}
}
]
}
]
}
};
```_
## Plugins
### HTML Webpack Plugin
```javascript
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html',
filename: 'index.html',
inject: 'body'
})
]
};
```_
### CSS Plugins
```javascript
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [MiniCssExtractPlugin.loader, 'css-loader']
}
]
},
plugins: [
new MiniCssExtractPlugin({
filename: '[name].[contenthash].css'
})
]
};
```_
### Plugin definieren
```javascript
const webpack = require('webpack');
module.exports = {
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production'),
'process.env.API_URL': JSON.stringify('https://api.example.com')
})
]
};
```_
### Webpack Plugin kopieren
```javascript
const CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = {
plugins: [
new CopyWebpackPlugin({
patterns: [
{ from: 'public', to: 'public' },
{ from: 'assets/images', to: 'images' }
]
})
]
};
```_
### Das ist die richtige Lösung. Plugins
```javascript
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
module.exports = {
plugins: [
new BundleAnalyzerPlugin({
analyzerMode: 'static',
openAnalyzer: false
})
]
};
```_
### Clean Webpack Plugin
```javascript
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
plugins: [
new CleanWebpackPlugin()
]
};
```_
## Modus
### Entwicklungsmodus
```javascript
module.exports = {
mode: 'development',
devtool: 'eval-source-map'
};
```_
### Produktionsmodus
```javascript
module.exports = {
mode: 'production',
devtool: 'source-map'
};
```_
### Modenspezifisch Konfiguration
```javascript
module.exports = (env, argv) => {
const isProduction = argv.mode === 'production';
return {
mode: argv.mode,
devtool: isProduction ? 'source-map' : 'eval-source-map',
optimization: {
minimize: isProduction
}
};
};
```_
## Entwicklungsserver
### Grundlegende Dev Server
```javascript
module.exports = {
devServer: {
static: './dist',
port: 3000,
open: true
}
};
```_
### Advanced Dev Server Konfiguration
```javascript
module.exports = {
devServer: {
static: {
directory: path.join(__dirname, 'dist')
},
compress: true,
port: 3000,
hot: true,
open: true,
historyApiFallback: true,
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
}
};
```_
### HTTPS Dev Server
```javascript
module.exports = {
devServer: {
https: true,
// or with custom certificates
https: {
key: fs.readFileSync('/path/to/server.key'),
cert: fs.readFileSync('/path/to/server.crt'),
ca: fs.readFileSync('/path/to/ca.pem')
}
}
};
```_
## Code Splitting
### Entry Point Split
```javascript
module.exports = {
entry: {
main: './src/index.js',
vendor: './src/vendor.js'
}
};
```_
### Dynamische Importe
```javascript
// In your JavaScript code
import('./math.js').then(math => {
console.log(math.add(16, 26));
});
// Or with async/await
async function loadMath() {
const math = await import('./math.js');
return math.add(16, 26);
}
```_
### SplitChunks Plugin
```javascript
module.exports = {
optimization: {
splitChunks: {
chunks: 'all',
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all'
},
common: {
name: 'common',
minChunks: 2,
chunks: 'all',
enforce: true
}
}
}
}
};
```_
### Erweiterte Code Splitting
```javascript
module.exports = {
optimization: {
splitChunks: {
chunks: 'all',
minSize: 20000,
maxSize: 244000,
cacheGroups: {
default: {
minChunks: 2,
priority: -20,
reuseExistingChunk: true
},
vendor: {
test: /[\\/]node_modules[\\/]/,
priority: -10,
reuseExistingChunk: true
},
react: {
test: /[\\/]node_modules[\\/](react|react-dom)[\\/]/,
name: 'react',
chunks: 'all'
}
}
}
}
};
```_
## Optimierung
### Bergbau
```javascript
const TerserPlugin = require('terser-webpack-plugin');
module.exports = {
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
terserOptions: {
compress: {
drop_console: true
}
}
})
]
}
};
```_
### CSS Optimierung
```javascript
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
module.exports = {
optimization: {
minimizer: [
new CssMinimizerPlugin()
]
}
};
```_
### Tree Shaking
```javascript
module.exports = {
mode: 'production',
optimization: {
usedExports: true,
sideEffects: false
}
};
```_
### Laufende Zeit Chunk
```javascript
module.exports = {
optimization: {
runtimeChunk: 'single'
}
};
```_
### Modulverkleidung
```javascript
module.exports = {
optimization: {
concatenateModules: true
}
};
```_
## Modul Auflösung
### Resolve Konfiguration
```javascript
const path = require('path');
module.exports = {
resolve: {
extensions: ['.js', '.jsx', '.ts', '.tsx', '.json'],
alias: {
'@': path.resolve(__dirname, 'src'),
'components': path.resolve(__dirname, 'src/components'),
'utils': path.resolve(__dirname, 'src/utils')
},
modules: [
'node_modules',
path.resolve(__dirname, 'src')
]
}
};
```_
### Zurück zur Übersicht
```javascript
module.exports = {
resolve: {
fallback: {
"fs": false,
"path": require.resolve("path-browserify"),
"crypto": require.resolve("crypto-browserify")
}
}
};
```_
## Hot Modul Ersatz
### HMR aktivieren
```javascript
const webpack = require('webpack');
module.exports = {
devServer: {
hot: true
},
plugins: [
new webpack.HotModuleReplacementPlugin()
]
};
```_
### HMR in Code
```javascript
// In your JavaScript modules
if (module.hot) {
module.hot.accept('./library.js', function() {
console.log('Accepting the updated library module!');
// Re-render or update your app
});
}
```_
### React Hot Reload
```javascript
const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
module.exports = {
module: {
rules: [
{
test: /\.[jt]sx?$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
plugins: ['react-refresh/babel']
}
}
]
}
]
},
plugins: [
new ReactRefreshWebpackPlugin()
]
};
```_
## Umweltvariablen
### DefinePlugin für Umweltvariablen
```javascript
const webpack = require('webpack');
module.exports = {
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
'process.env.API_URL': JSON.stringify(process.env.API_URL || 'http://localhost:3000')
})
]
};
```_
### Umweltspezifische Konfiguration
```javascript
module.exports = (env, argv) => {
const isProduction = argv.mode === 'production';
return {
mode: argv.mode,
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(argv.mode),
'process.env.API_URL': JSON.stringify(
isProduction ? 'https://api.production.com' : 'http://localhost:3000'
)
})
]
};
};
```_
### DotEnv Plugin
```javascript
const Dotenv = require('dotenv-webpack');
module.exports = {
plugins: [
new Dotenv({
path: './.env',
safe: true,
systemvars: true
})
]
};
```_
## Produktionsaufbau
### Produktionskonfiguration
```javascript
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
module.exports = {
mode: 'production',
entry: './src/index.js',
output: {
filename: '[name].[contenthash].js',
path: path.resolve(__dirname, 'dist'),
clean: true
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env']
}
}
},
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, 'css-loader']
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html',
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true
}
}),
new MiniCssExtractPlugin({
filename: '[name].[contenthash].css'
})
],
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
terserOptions: {
compress: {
drop_console: true
}
}
}),
new CssMinimizerPlugin()
],
splitChunks: {
chunks: 'all',
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all'
}
}
},
runtimeChunk: 'single'
}
};
```_
### Skripte erstellen
```json
{
"scripts": {
"build": "webpack --mode production",
"build:analyze": "webpack --mode production --env analyze",
"build:stats": "webpack --mode production --json > stats.json"
}
}
```_
## Erweiterte Konfiguration
### Mehrseitige Anwendung
```javascript
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
home: './src/home.js',
about: './src/about.js',
contact: './src/contact.js'
},
plugins: [
new HtmlWebpackPlugin({
filename: 'home.html',
template: './src/home.html',
chunks: ['home']
}),
new HtmlWebpackPlugin({
filename: 'about.html',
template: './src/about.html',
chunks: ['about']
}),
new HtmlWebpackPlugin({
filename: 'contact.html',
template: './src/contact.html',
chunks: ['contact']
})
]
};
```_
### Mikrofrontends Konfiguration
```javascript
const ModuleFederationPlugin = require('@module-federation/webpack');
module.exports = {
plugins: [
new ModuleFederationPlugin({
name: 'shell',
remotes: {
mfe1: 'mfe1@http://localhost:3001/remoteEntry.js',
mfe2: 'mfe2@http://localhost:3002/remoteEntry.js'
}
})
]
};
```_
### Fortschrittliche Web-App
```javascript
const WorkboxPlugin = require('workbox-webpack-plugin');
module.exports = {
plugins: [
new WorkboxPlugin.GenerateSW({
clientsClaim: true,
skipWaiting: true
})
]
};
```_
### Kundenspezifische Lasten
```javascript
// custom-loader.js
module.exports = function(source) {
// Transform the source
return `export default ${JSON.stringify(source)}`;
};
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.custom$/,
use: path.resolve(__dirname, 'custom-loader.js')
}
]
}
};
```_
### Individuelle Plugins
```javascript
class MyCustomPlugin {
apply(compiler) {
compiler.hooks.emit.tapAsync('MyCustomPlugin', (compilation, callback) => {
console.log('This is an example plugin!');
callback();
});
}
}
module.exports = {
plugins: [
new MyCustomPlugin()
]
};
```_
## Leistung
### Leistungshaushalte
```javascript
module.exports = {
performance: {
maxAssetSize: 250000,
maxEntrypointSize: 250000,
hints: 'warning'
}
};
```_
### Lazy Loading
```javascript
// Dynamic imports for lazy loading
const LazyComponent = React.lazy(() => import('./LazyComponent'));
// Webpack magic comments
import(
/* webpackChunkName: "my-chunk-name" */
/* webpackMode: "lazy" */
'./modules/my-module.js'
);
```_
### Prefetching und Preloading
```javascript
// Prefetch
import(
/* webpackPrefetch: true */
'./modules/LoginModal.js'
);
// Preload
import(
/* webpackPreload: true */
'./modules/ChartingLibrary.js'
);
```_
### Bundanalyse
```bash
# Generate stats file
webpack --profile --json > stats.json
# Analyze with webpack-bundle-analyzer
npx webpack-bundle-analyzer stats.json
# Use webpack-bundle-analyzer plugin
npm install --save-dev webpack-bundle-analyzer
Fehlerbehebung¶
Gemeinsame Themen und Lösungen¶
Nicht gefunden¶
javascript
// Check resolve configuration
module.exports = {
resolve: {
extensions: ['.js', '.jsx', '.ts', '.tsx'],
alias: {
'@': path.resolve(__dirname, 'src')
}
}
};_
Speicherprobleme¶
```bash
Increase Node.js memory limit¶
node --max-old-space-size=4096 node_modules/.bin/webpack
Or in package.json¶
{ "scripts": { "build": "node --max-old-space-size=4096 node_modules/.bin/webpack" } } ```_
Slow Build Times¶
```javascript module.exports = { // Use cache cache: { type: 'filesystem' },
// Exclude node_modules from babel-loader module: { rules: [ { test: /.js$/, exclude: /node_modules/, use: 'babel-loader' } ] },
// Use thread-loader for expensive loaders module: { rules: [ { test: /.js$/, use: [ 'thread-loader', 'babel-loader' ] } ] } }; ```_
Quelle Map Issues¶
javascript
module.exports = {
// Different source map options
devtool: 'eval-source-map', // Development
devtool: 'source-map', // Production
devtool: 'cheap-module-source-map', // Faster builds
devtool: false // No source maps
};_
Debugging Konfiguration¶
javascript
module.exports = {
stats: {
colors: true,
modules: false,
children: false,
chunks: false,
chunkModules: false
}
};_
Best Practices¶
Konfigurationsorganisation¶
```javascript // webpack.common.js const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = { entry: './src/index.js', plugins: [ new HtmlWebpackPlugin({ template: './src/index.html' }) ] };
// webpack.dev.js const { merge } = require('webpack-merge'); const common = require('./webpack.common.js');
module.exports = merge(common, { mode: 'development', devtool: 'eval-source-map', devServer: { static: './dist' } });
// webpack.prod.js const { merge } = require('webpack-merge'); const common = require('./webpack.common.js');
module.exports = merge(common, { mode: 'production', devtool: 'source-map' }); ```_
Leistungsoptimierung¶
- ** Produktionsmodus** für Optimierungen
- Enable tree shaking to remove dead code
- Einzelstücke zur Verbesserung des Cachings
- **Verwenden von Inhalten ** für langfristiges Caching
- Minimize Bündelgröße mit richtigen Lader und Plugins
Erfahrung in der Entwicklung¶
- ** Verwenden Sie HMR** für schnellere Entwicklung
- ** Quellkarten konfigurieren* für Debugging
- Einrichten von dev Server mit Proxy für API-Anrufe
- Verwenden Sie Webpack-bundle-analyzer, um Bündelzusammensetzung zu verstehen
Code Organisation¶
- Separate Konfiguration für verschiedene Umgebungen
- Diese Alias für sauberere Einfuhren
- Beladegeräte nach Dateityp
- Gruppenbezogene Plugins zusammen
--
Zusammenfassung¶
Webpack ist ein leistungsstarker und flexibler Modulbündelr, der komplexe Bauanforderungen für moderne Webanwendungen bewältigen kann. Zu den wichtigsten Merkmalen gehören:
- Modul Bundling: Kombiniert Module in optimierte Bündel
- Loaders: Dateien während des Build-Prozesses transformieren
- **Plugins*: Webpack-Funktionalität erweitern
- ** Code Splitting**: Split Code in kleinere Stücke für bessere Leistung
- Hot Modul Ersatz: Module ohne vollständige Seitenumladung aktualisieren
- **Tree Shaking*: Nicht verwendeter Code aus Bündeln entfernen
- Asset Management: Geben Sie verschiedene Dateitypen und Assets aus
Durch die Webpack-Konfiguration und nach Best Practices können Sie effiziente Build-Prozesse erstellen, die sowohl Entwicklungserfahrung als auch Anwendungsleistung verbessern.
<= <= <= <================================================================================= Funktion copyToClipboard() {\cHFFFF} const commands = document.querySelectorAll('code'); alle Befehle = ''; Befehle. Für jede(cmd) => alle Befehle += cmd.textContent + '\n'); navigator.clipboard.writeText (allCommands); Alarm ('Alle Befehle, die in die Zwischenablage kopiert werden!'); }
Funktion generierenPDF() { Fenster.print(); }