Panduan Pengguna
Panduan ini mencakup fungsionalitas inti webpack, termasuk opsi konfigurasi, penggunaan CLI, dan praktik terbaik untuk Webpack 4 dan Webpack 5.
Konfigurasi
Webpack dikonfigurasi melalui file JavaScript bernama webpack.config.js secara default. File ini mengekspor objek konfigurasi yang memberi tahu webpack cara membangun proyek Anda.
Konfigurasi Dasar
// 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'),
},
};
Jenis Konfigurasi
Webpack mendukung beberapa jenis file konfigurasi:
| Jenis | Webpack 4 | Webpack 5 | Deskripsi |
|---|---|---|---|
| CommonJS | ✅ | ✅ | module.exports = {} |
| Modul ES | ⚠️ Terbatas | ✅ Penuh | export default {} |
| TypeScript | ⚠️ Dengan ts-node | ✅ Native | File .ts |
| Beberapa Konfigurasi | ✅ | ✅ | Array konfigurasi |
Titik Masuk
Titik masuk memberi tahu webpack di mana harus mulai membangun grafik dependensi.
Entry Tunggal
// Webpack 4 & 5
module.exports = {
entry: './src/index.js',
};
Beberapa Entry
// Webpack 4 & 5
module.exports = {
entry: {
main: './src/index.js',
vendor: './src/vendor.js',
},
};
Entry Dinamis
// Webpack 4 & 5
module.exports = {
entry: {
page1: './src/page1.js',
page2: './src/page2.js',
},
};
Objek Entry dengan Array
// Webpack 4 & 5
module.exports = {
entry: {
app: ['./src/index.js', './src/another.js'],
},
};
Output
Konfigurasi output memberi tahu webpack di mana harus mengeluarkan bundel yang dibuatnya.
Output Dasar
// Webpack 4 & 5
module.exports = {
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
};
Output Bernama dengan [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 dengan [hash] dan [chunkhash]
// Webpack 4 & 5
module.exports = {
output: {
filename: '[name].[contenthash].js',
path: path.resolve(__dirname, 'dist'),
clean: true, // Webpack 5 only - cleans dist folder
},
};
Perbandingan Konfigurasi
| Fitur | Webpack 4 | Webpack 5 |
|---|---|---|
| Output.clean | ❌ Tidak tersedia | ✅ Membersihkan folder dist secara otomatis |
| Output.pathinfo | ✅ Default true | ✅ Default false (production) |
| Output.hashFunction | MD4 | MD4 (default), md4, xxHash64, bubblehash |
| Output.module | ❌ Tidak tersedia | ✅ Output sebagai modul ES |
| Output.environment | ❌ Tidak tersedia | ✅ Pengaturan dukungan modul ES |
Loaders
Loader memungkinkan webpack memproses lebih dari sekadar file JavaScript.
Konfigurasi Loader Dasar
// Webpack 4 & 5
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
{
test: /\.js$/,
exclude: /node_modules/,
use: 'babel-loader',
},
],
},
};
Opsi Loader
// 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 (Hanya Webpack 5)
Webpack 5 memperkenalkan Asset Modules sebagai pengganti file-loader, url-loader, dan 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',
},
],
},
};
Perbandingan Loader
| Jenis Loader | Webpack 4 | Webpack 5 | Modul Pengganti |
|---|---|---|---|
| file-loader | Diperlukan | ✅ Alternatif | asset/resource |
| url-loader | Diperlukan | ✅ Alternatif | asset |
| raw-loader | Diperlukan | ✅ Alternatif | asset/source |
| svg-url-loader | Diperlukan | ✅ Alternatif | Pemrosesan kustom |
Plugins
Plugin melakukan tugas yang lebih luas daripada loader, mulai dari optimasi bundel hingga injeksi variabel lingkungan.
Konfigurasi Plugin Dasar
// 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'),
}),
],
};
Plugin Umum
| Plugin | Deskripsi | Webpack 4 | Webpack 5 |
|---|---|---|---|
| html-webpack-plugin | Menghasilkan file HTML | ✅ | ✅ |
| mini-css-extract-plugin | Mengekstrak CSS ke file terpisah | ✅ | ✅ |
| clean-webpack-plugin | Membersihkan direktori output | ✅ | ✅ |
| terser-webpack-plugin | Memperkecil JavaScript | ✅ | ✅ |
| filemanager-webpack-plugin | Operasi sistem file | ✅ | ✅ |
| module-federation-plugin | Module Federation | ❌ | ✅ |
Plugin Bawaan Webpack 5
Webpack 5 mencakup beberapa plugin yang bersifat eksternal di Webpack 4:
| Plugin | Webpack 4 | Webpack 5 |
|---|---|---|
| asset-plugins | Diperlukan | ✅ Bawaan |
| module-federation | Diperlukan | ✅ Bawaan |
| persistent-cache | Diperlukan | ✅ Bawaan |
Mode
Webpack menyediakan tiga opsi mode bawaan: development, production, dan 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'),
},
};
Optimasi Khusus Mode
| Optimasi | 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 |
Alat Pengembangan
Source Maps
Source map membantu men-debug kode yang dikompilasi dengan memetakannya kembali ke sumber asli.
| Opsi | Webpack 4 | Webpack 5 | Deskripsi |
|---|---|---|---|
eval | ✅ | ✅ | Tercepat, dibungkus dalam eval() |
cheap-eval-source-map | ✅ | ✅ | Baik untuk pengembangan |
cheap-module-eval-source-map | ✅ | ✅ | Mempertahankan sumber asli |
source-map | ✅ | ✅ | Kualitas terbaik, paling lambat |
hidden-source-map | ✅ | ✅ | Tidak direferensikan dalam bundel |
eval-source-map | ✅ | ✅ | Bekerja dengan eval() |
Webpack Dev Server
Webpack Dev Server menyediakan server pengembangan dengan pemuatan ulang langsung.
// 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,
},
};
Perbandingan Konfigurasi
| Fitur | Webpack 4 | Webpack 5 |
|---|---|---|
| devServer.static | directory sebagai string | objek dengan properti directory |
| devServer.contentBase | ✅ Tidak digunakan lagi | ❌ Dihapus |
| watchOptions | Properti langsung | Properti langsung |
| server | ❌ Tidak tersedia | ✅ Konfigurasi server baru |
Code Splitting
Webpack dapat memisahkan kode Anda menjadi beberapa bundel untuk performa yang lebih baik.
Impor Dinamis (Webpack 4 & 5)
// Webpack 4 & 5
button.addEventListener('click', () => {
import('./module').then((module) => {
module.default();
});
});
Komentar Ajaib (Webpack 4 & 5)
// Webpack 4 & 5
import(
/* webpackChunkName: "my-chunk" */
/* webpackMode: "lazy" */
'./module'
).then((module) => {
module.default();
});
Konfigurasi SplitChunks
// Webpack 4 & 5
module.exports = {
optimization: {
splitChunks: {
chunks: 'all',
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all',
},
},
},
},
};
Perbandingan Konfigurasi
| Fitur | Webpack 4 | Webpack 5 |
|---|---|---|
| optimization.splitChunks.cacheGroups | ✅ | ✅ |
| optimization.chunkGroups | ❌ Tidak tersedia | ✅ Tersedia |
| optimization.moduleConcatenation | ✅ (Optimization.concatenateModules) | ✅ (Optimization.concatenateModules) |
| fetchPriority | ❌ Tidak tersedia | ✅ Tersedia untuk import() |
Module Federation (Hanya Webpack 5)
Module Federation adalah fitur baru di Webpack 5 yang memungkinkan berbagi kode antar build yang berbeda saat runtime.
Konfigurasi Host
// 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'],
}),
],
};
Konfigurasi Remote
// 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'],
}),
],
};
Fitur ini tidak tersedia di Webpack 4 dan memerlukan plugin pihak ketiga untuk fungsionalitas serupa.
Performa
Webpack menyediakan beberapa opsi untuk meningkatkan performa build.
Petunjuk Performa
// Webpack 4 & 5
module.exports = {
performance: {
hints: 'warning', // or 'error' or false
maxAssetSize: 200000,
maxEntrypointSize: 400000,
},
};
Konfigurasi Cache
// 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'),
},
};
Perbandingan Konfigurasi
| Fitur | Webpack 4 | Webpack 5 |
|---|---|---|
| cache.type | ❌ Tidak tersedia | ✅ 'memory' atau 'filesystem' |
| buildDependencies | ❌ Tidak tersedia | ✅ Melacak perubahan file konfigurasi |
| managedPaths | ❌ Tidak tersedia | ✅ Mengoptimalkan caching di macOS/Linux |
Referensi CLI
Perintah Dasar
| Perintah | Deskripsi |
|---|---|
webpack | Menjalankan build webpack |
webpack build | Menjalankan build webpack (eksplisit) |
webpack watch | Memantau perubahan file |
webpack serve | Menjalankan webpack-dev-server |
webpack info | Menampilkan informasi sistem |
webpack configtest | Memvalidasi konfigurasi webpack |
Flag Umum
| Flag | Deskripsi |
|---|---|
--mode development | Mengatur mode ke development |
--mode production | Mengatur mode ke production |
--config webpack.config.js | Menggunakan file konfigurasi kustom |
--entry ./src/index.js | Mengatur titik masuk |
-o, --output-path ./dist | Mengatur direktori output |
-w, --watch | Memantau perubahan |
--devtool source-map | Mengatur opsi source map |
--json | Menampilkan statistik sebagai JSON |
--progress | Menampilkan kemajuan kompilasi |
Perbandingan Konfigurasi
| Fitur | Webpack 4 | Webpack 5 |
|---|---|---|
| --env | Hanya nilai string | Nilai objek didukung |
| --config-node-env | ❌ Tidak tersedia | ✅ Mengatur process.env.NODE_ENV |
| --analyze | Memerlukan plugin | ✅ Dukungan bawaan |
| --info | Output dasar | Output yang ditingkatkan |
Variabel Lingkungan
Webpack menyediakan beberapa variabel lingkungan bawaan:
| Variabel | Deskripsi |
|---|---|
WEBPACK_SERVE | true jika webpack-dev-server sedang digunakan |
WEBPACK_BUILD | true jika build sedang digunakan |
WEBPACK_WATCH | true jika watch sedang digunakan |
Contoh Penggunaan
// Webpack 4 & 5
module.exports = (env, argv) => {
return {
mode: argv.mode || 'development',
devServer: argv.WEBPACK_SERVE ? {
static: './dist',
} : undefined,
};
};
Praktik Terbaik
Pengaturan Konfigurasi
// 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,
},
};
};
Praktik Terbaik Khusus Versi
Webpack 4
- Gunakan
file-loader,url-loaderuntuk aset - Konfigurasikan caching dengan
cache-loader - Gunakan
optimization.concatenateModulesuntuk scope hoisting - Gunakan
ExtractTextPluginuntuk ekstraksi CSS
Webpack 5
- Gunakan Asset Modules sebagai pengganti file-loader/url-loader
- Aktifkan
cache.type = 'filesystem'untuk build ulang yang lebih cepat - Gunakan Module Federation bawaan untuk micro-frontend
- Gunakan
_magic_commentsuntuk optimasi import()
Migrasi dari Webpack 4 ke Webpack 5
Langkah 1: Perbarui Node.js
Webpack 5 memerlukan Node.js 10.13.0 atau lebih baru:
# Check your version
node -v
# Update if needed
nvm install 14
nvm use 14
Langkah 2: Ganti Loader dengan Asset Modules
Webpack 4:
{
test: /\.(png|jpg|gif)$/,
use: 'file-loader'
}
Webpack 5:
{
test: /\.(png|jpg|gif)$/,
type: 'asset/resource'
}
Langkah 3: Aktifkan Caching Persisten
Webpack 4: Memerlukan plugin eksternal Webpack 5: Bawaan
cache: {
type: 'filesystem',
},
Langkah 4: Perbarui Ekstraksi CSS
Webpack 4:
npm install extract-text-webpack-plugin --save-dev
Webpack 5:
npm install mini-css-extract-plugin --save-dev
Langkah 5: Perbarui Penggunaan Plugin
Beberapa plugin telah diganti atau diperbarui di Webpack 5. Periksa dokumentasi plugin untuk kompatibilitas.
