FAQ
Dokumen ini menjawab pertanyaan yang sering diajukan tentang webpack, dengan perhatian khusus pada perbedaan antara Webpack 4 dan Webpack 5.
Instalasi
T1: Apa persyaratan sistem untuk webpack?
Webpack 4:
- Node.js 6.x.x atau lebih baru
- npm 3.x.x atau lebih baru
Webpack 5:
- Node.js 10.13.0 atau lebih baru
- npm 6.x.x atau lebih baru
- Rekomendasi: Node.js 12.x.x atau lebih baru untuk performa terbaik
T2: Di mana saya harus menginstal webpack - global atau lokal?
J: Instal webpack secara lokal untuk setiap proyek. Instalasi global tidak disarankan karena:
- Proyek yang berbeda mungkin memerlukan versi webpack yang berbeda
- Instalasi lokal memberikan kontrol versi yang lebih baik
- Anggota tim mendapatkan versi yang konsisten
# Local installation (recommended)
npm install webpack webpack-cli --save-dev
# Global installation (not recommended)
npm install -g webpack
T3: Mengapa saya mendapatkan error "Could not find webpack-cli"?
Error ini terjadi ketika webpack-cli tidak diinstal. Instal sebagai dependensi dev:
# For Webpack 4
npm install webpack-cli@4 --save-dev
# For Webpack 5
npm install webpack-cli@5 --save-dev
T4: Saya mendapatkan error "Node.js version too old" saat menginstal Webpack 5
Webpack 5 memerlukan Node.js 10.13.0 atau lebih baru. Periksa versi Anda:
node -v
# If version is older than v10.13.0, update:
nvm install 14 # if you have nvm
nvm use 14
Konfigurasi
T5: Apa perbedaan antara konfigurasi Webpack 4 dan Webpack 5?
Webpack 4:
- Memerlukan sintaks CommonJS (
module.exports = {}) - Dukungan modul ES terbatas
- Tidak ada caching persisten bawaan
Webpack 5:
- Mendukung CommonJS dan modul ES
- Dukungan modul ES penuh dengan
export default {} - Caching persisten bawaan
// Webpack 4 (CommonJS only)
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
},
};
// Webpack 5 (ES modules)
import path from 'node:path';
export default {
entry: './src/index.js',
output: {
path: path.resolve(import.meta.dirname, 'dist'),
filename: 'bundle.js',
},
};
T6: Mengapa konfigurasi saya mengembalikan fungsi?
Webpack mendukung beberapa format file konfigurasi:
// Object configuration (works in both versions)
module.exports = {
entry: './src/index.js',
};
// Function configuration (works in both versions)
module.exports = (env, argv) => {
return {
mode: argv.mode || 'development',
entry: './src/index.js',
};
};
// Promise configuration (works in both versions)
module.exports = () => {
return new Promise((resolve, reject) => {
resolve({
entry: './src/index.js',
});
});
};
// Array of configurations (works in both versions)
module.exports = [
{
entry: './src/index.js',
output: { filename: 'index.js' },
},
{
entry: './src/vendor.js',
output: { filename: 'vendor.js' },
},
];
T7: Apa tujuan clean: true dalam konfigurasi output?
Opsi clean: true secara otomatis menghapus semua file dari direktori output sebelum setiap build.
Webpack 4:
- Memerlukan plugin
clean-webpack-plugin
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
plugins: [
new CleanWebpackPlugin(),
],
Webpack 5:
- Opsi bawaan
output: {
clean: true,
},
Loaders
T8: Apa yang terjadi pada file-loader, url-loader, dan raw-loader di Webpack 5?
Webpack 5 menggantikan loader ini dengan Asset Modules bawaan:
| Loader Webpack 4 | Asset Module Webpack 5 |
|---|---|
| file-loader | asset/resource |
| url-loader | asset (dengan batas ukuran) |
| raw-loader | asset/source |
Webpack 4:
module.exports = {
module: {
rules: [
{
test: /\.png$/,
use: 'file-loader',
},
{
test: /\.svg$/,
use: 'url-loader?limit=10000',
},
{
test: /\.txt$/,
use: 'raw-loader',
},
],
},
};
Webpack 5:
module.exports = {
module: {
rules: [
{
test: /\.png$/,
type: 'asset/resource',
},
{
test: /\.svg$/,
type: 'asset',
parser: {
dataUrlCondition: {
maxSize: 10000, // 10kb
},
},
},
{
test: /\.txt$/,
type: 'asset/source',
},
],
},
};
T9: Mengapa CSS saya tidak diekstrak?
Di Webpack 4, Anda memerlukan extract-text-webpack-plugin. Di Webpack 5, gunakan mini-css-extract-plugin.
Webpack 4:
npm install extract-text-webpack-plugin@next --save-dev
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: 'css-loader',
}),
},
],
},
plugins: [
new ExtractTextPlugin('styles.css'),
],
};
Webpack 5:
npm install mini-css-extract-plugin --save-dev
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, 'css-loader'],
},
],
},
plugins: [
new MiniCssExtractPlugin({
filename: 'styles.css',
}),
],
};
Khusus Webpack 4 vs Webpack 5
T10: Fitur utama apa yang baru di Webpack 5?
- Module Federation: Berbagi kode antar build yang berbeda saat runtime
- Caching Persisten: Caching bawaan untuk mempercepat build
- Asset Modules: menggantikan file-loader, url-loader, dan raw-loader
- Dukungan Modul ES yang Ditingkatkan: Penanganan modul ES yang lebih baik
- Peningkatan Chunk ID: Nama chunk deterministik secara default
- Komentar Sumber Daya: Komentar ajaib baru untuk optimasi import()
- Penanganan Konten Remote: Penanganan konten eksternal yang ditingkatkan
T11: Bagaimana cara menggunakan Module Federation (hanya Webpack 5)?
Module Federation adalah fitur khusus Webpack 5 untuk arsitektur micro-frontend.
Aplikasi Host:
// webpack.config.js
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'],
}),
],
};
Aplikasi Remote:
// webpack.config.js
const ModuleFederationPlugin = require('webpack').container.ModuleFederationPlugin;
module.exports = {
plugins: [
new ModuleFederationPlugin({
name: 'remote',
filename: 'remoteEntry.js',
exposes: {
'./Button': './src/Button',
},
shared: ['react', 'react-dom'],
}),
],
};
Di Webpack 4: Fitur ini tidak ada dan memerlukan plugin pihak ketiga seperti @scriptedalchemy/webpack-remote.
T12: Bagaimana cara mengaktifkan caching persisten di Webpack 4 vs 5?
Webpack 4: Memerlukan plugin eksternal seperti cache-loader:
npm install cache-loader --save-dev
module.exports = {
module: {
rules: [
{
test: /\.js$/,
use: ['cache-loader', 'babel-loader'],
},
],
},
};
Webpack 5: Caching persisten bawaan:
module.exports = {
cache: {
type: 'filesystem', // 'memory' is default (no build speed benefit)
cacheDirectory: path.resolve(__dirname, '.webpack_cache'),
},
};
Code Splitting
T13: Apa perbedaan antara dynamic import dan require.ensure?
Dynamic Import (standar ES2020):
- Didukung di Webpack 4 dan Webpack 5
- Sintaks standar modern
- Bekerja dengan async/await
- Mendukung komentar ajaib
// Webpack 4 & 5
import('./module').then((module) => {
module.default();
});
// With async/await
const module = await import('./module');
require.ensure (Legacy khusus webpack):
- Didukung di Webpack 4 dan Webpack 5
- Sintaks legacy khusus webpack
- Bukan fitur JavaScript standar
- Berbasis callback
// Webpack 4 & 5
require.ensure(['./module'], (require) => {
const module = require('./module');
});
T14: Bagaimana cara menggunakan komentar ajaib untuk impor dinamis?
Komentar ajaib memberikan direktif kepada webpack untuk impor dinamis.
// Webpack 4 & 5
import(
/* webpackChunkName: "my-chunk" */
/* webpackMode: "lazy" */
/* webpackPrefetch: true */
/* webpackPreload: true */
'./module'
).then((module) => {
module.default();
});
Perbandingan Komentar Ajaib:
| Komentar | Webpack 4 | Webpack 5 | Deskripsi |
|---|---|---|---|
webpackChunkName | ✅ | ✅ | Nama untuk chunk |
webpackMode | ✅ | ✅ | Mode pemuatan (lazy, eager, weak) |
webpackPrefetch | ✅ | ✅ | Prefetch chunk |
webpackPreload | ✅ | ✅ | Preload chunk |
webpackExports | ❌ | ✅ | Membatasi nama yang diekspor (hanya Webpack 5+) |
webpackFetchPriority | ❌ | ✅ | Mengatur prioritas fetch (Webpack 5.87.0+) |
T15: Bagaimana cara mengoptimalkan code splitting?
Webpack 4:
module.exports = {
optimization: {
splitChunks: {
chunks: 'all',
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all',
},
},
},
},
};
Webpack 5: Konfigurasi yang sama berfungsi, tetapi dengan optimasi tambahan:
module.exports = {
optimization: {
splitChunks: {
chunks: 'all',
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all',
priority: -10,
},
},
},
},
};
Performa
T16: Bagaimana cara mempercepat build saya?
Tips Umum:
- Aktifkan Caching
Webpack 4:
module.exports = {
cache: false,
// Use cache-loader for specific loaders
};
Webpack 5:
module.exports = {
cache: {
type: 'filesystem',
},
};
- Gunakan webpack-dev-server untuk pengembangan
npx webpack serve
- Aktifkan build paralel
Webpack 4 & 5:
module.exports = {
module: {
rules: [
{
test: /\.js$/,
use: {
loader: 'babel-loader',
options: {
cacheDirectory: true,
},
},
},
],
},
};
T17: Apa perbedaan antara performa Webpack 4 dan Webpack 5?
Peningkatan Webpack 5:
- Build lebih cepat: Penelusuran grafik dependensi yang ditingkatkan
- Caching lebih baik: Caching persisten secara default
- Tree shaking yang ditingkatkan: Dukungan modul ES yang lebih baik
- Serialisasi lebih cepat: Serialisasi modul yang ditingkatkan
Perbandingan Performa:
| Metrik | Webpack 4 | Webpack 5 |
|---|---|---|
| Build Awal | 100% | 80-90% |
| Build Ulang (cache) | 100% | 30-40% |
| Tree Shaking | Baik | Sangat baik |
| Pembuatan Source Map | Sedang | Cepat |
Plugins
T18: Apa yang terjadi pada hard-source-webpack-plugin?
Hard-source-webpack-plugin adalah plugin caching populer untuk Webpack 4. Di Webpack 5, fungsionalitasnya sudah bawaan:
Webpack 4:
npm install hard-source-webpack-plugin --save-dev
const HardSourceWebpackPlugin = require('hard-source-webpack-plugin');
module.exports = {
plugins: [
new HardSourceWebpackPlugin(),
],
};
Webpack 5:
module.exports = {
cache: {
type: 'filesystem',
},
};
T19: Plugin apa yang direkomendasikan untuk Webpack 5?
Plugin Inti:
| Plugin | Tujuan | Webpack 4 | Webpack 5 |
|---|---|---|---|
html-webpack-plugin | Pembuatan HTML | ✅ | ✅ |
mini-css-extract-plugin | Ekstraksi CSS | ✅ | ✅ |
clean-webpack-plugin | Membersihkan output | ✅ | ✅ |
terser-webpack-plugin | Minifikasi JS | ✅ | ✅ |
webpack-bundle-analyzer | Analisis bundel | ✅ | ✅ |
module-federation-plugin | Berbagi modul | ❌ | ✅ (bawaan) |
T20: Bagaimana cara menganalisis ukuran bundel?
Webpack 4 & 5:
# Install
npm install webpack-bundle-analyzer --save-dev
# Configuration
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
module.exports = {
plugins: [
new BundleAnalyzerPlugin(),
],
};
Runtime dan API
T21: Apa itu webpack_require?
__webpack_require__ adalah fungsi runtime webpack yang memuat modul.
// In your bundled code, this becomes:
var __webpack_require__ = __webpack_require__ || (() => {
// webpack runtime code
})();
// Your code:
const myModule = __webpack_require__('./my-module.js');
T22: Apa perbedaan antara require dan import di webpack?
require (CommonJS):
- Pemuatan sinkron
- Resolusi saat runtime
- Berfungsi di Webpack 4 dan 5
import (Modul ES):
- Analisis statis
- Resolusi saat kompilasi
- Tree shaking yang lebih baik di Webpack 5
- Berfungsi di Webpack 4 dan 5
Jenis Modul
T23: Sintaks modul apa yang didukung webpack?
Webpack mendukung beberapa sintaks modul JavaScript:
| Sintaks | Status | Webpack 4 | Webpack 5 |
|---|---|---|---|
| CommonJS | Dukungan penuh | ✅ | ✅ |
| Modul ES6 | Dukungan penuh | ✅ | ✅ (lebih baik) |
| AMD | Dukungan penuh | ✅ | ✅ |
| ESM di .mjs | Dukungan penuh | ✅ | ✅ |
| CJS di .cjs | Dukungan penuh | ✅ | ✅ |
T24: Bagaimana cara mengonfigurasi webpack untuk TypeScript?
Webpack 4 & 5:
module.exports = {
resolve: {
extensions: ['.ts', '.tsx', '.js'],
},
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
};
Kesalahan dan Pemecahan Masalah
T25: Saya mendapatkan error "Module not found"
Penyebab dan solusi umum:
- Dependensi hilang:
npm install missing-package --save-dev
- Jalur salah:
- Periksa ekstensi file (.js, .ts, dll.)
- Periksa jalur relatif (./, ../)
- Periksa resolve.alias dalam konfigurasi
- Resolusi modul Node.js: Webpack 4 & 5:
resolve: {
modules: ['node_modules', 'additional_modules'],
alias: {
'@': path.resolve(__dirname, 'src'),
},
},
T26: Saya mendapatkan error "Chunk chunk-name was not found"
Error ini terjadi ketika mencoba memuat chunk yang tidak ada.
Solusi:
- Periksa bahwa impor dinamis memiliki jalur yang benar
- Verifikasi nama chunk di komentar ajaib
- Periksa konfigurasi output
T27: Webpack menggunakan terlalu banyak memori
Solusi:
- Tingkatkan memori Node.js:
node --max-old-space-size=4096 node_modules/webpack/bin/webpack.js
- Nonaktifkan plugin:
- Nonaktifkan sementara plugin yang intensif memori
- Gunakan source map yang lebih sederhana
- Peningkatan memori Webpack 5:
cache: {
type: 'filesystem',
maxMemoryProcesses: 2, // Limit concurrent processes
},
Migrasi Webpack 4 ke Webpack 5
T28: Bagaimana cara bermigrasi dari Webpack 4 ke Webpack 5?
Langkah 1: Perbarui dependensi
npm install webpack@latest webpack-cli@latest --save-dev
Langkah 2: Perbarui Node.js Pastikan Node.js 10.13.0 atau lebih baru terinstal.
Langkah 3: Ganti loader yang tidak digunakan lagi
- Ganti
file-loaderdenganasset/resource - Ganti
url-loaderdenganasset - Ganti
raw-loaderdenganasset/source
Langkah 4: Perbarui plugin
- Ganti
hard-source-webpack-plugindengan caching bawaan - Perbarui plugin ekstraksi CSS ke
mini-css-extract-plugin
Langkah 5: Uji build Anda Jalankan webpack dan perbaiki semua kesalahan.
T29: Build saya rusak setelah upgrade ke Webpack 5
Masalah umum dan perbaikannya:
Penamaan chunk: Webpack 5 menggunakan nama chunk deterministik secara default. Perbarui pengujian Anda jika bergantung pada nama chunk tertentu.
Penanganan aset: Perbarui konfigurasi Anda untuk menggunakan Asset Modules sebagai pengganti file-loader.
Module ID: Webpack 5 menggunakan algoritma module ID yang berbeda. Perbarui pengujian apa pun yang bergantung pada module ID tertentu.
Source map: Beberapa opsi source map telah berubah. Perbarui konfigurasi Anda.
Topik Lanjutan
T30: Bisakah saya menggunakan Webpack dengan monorepo?
Ya, Webpack bekerja dengan baik dengan monorepo menggunakan:
- Lerna dengan Webpack
- Yarn Workspaces dengan Webpack
- Module Federation (Webpack 5)
Contoh Module Federation (Webpack 5):
// In each package of your monorepo
const ModuleFederationPlugin = require('webpack').container.ModuleFederationPlugin;
module.exports = {
plugins: [
new ModuleFederationPlugin({
name: 'package-name',
filename: 'remoteEntry.js',
exposes: {
'./Component': './src/Component',
},
shared: ['react', 'react-dom'],
}),
],
};
T31: Apa batas ukuran modul/bundel di webpack?
Webpack tidak memiliki batas ukuran yang keras. Namun, pertimbangkan:
- Batas browser: Sebagian besar browser memiliki batas ukuran 200MB+
- Performa jaringan: Bundel besar memengaruhi waktu pemuatan
- Penggunaan memori: Bundel besar mengonsumsi lebih banyak memori
Praktik Terbaik: Jaga bundel awal di bawah 200KB (di-gzip) untuk performa optimal.
T32: Bagaimana webpack menangani tree shaking?
Tree shaking menghapus kode yang tidak terpakai dari bundel Anda.
Persyaratan:
- Gunakan modul ES6 (import/export)
- Atur
sideEffectsdi package.json - Gunakan
mode: 'production'atau aktifkan optimasi
Webpack 4 vs Webpack 5:
| Aspek | Webpack 4 | Webpack 5 |
|---|---|---|
| Dukungan Modul ES | Baik | Sangat baik |
| Deteksi Side Effects | Dasar | Lanjutan |
| Deteksi Ekspor | Dasar | Lanjutan |
T33: Bisakah saya menggunakan webpack dengan React, Vue, atau Angular?
Ya, webpack bekerja dengan semua kerangka kerja utama.
React:
npm install react react-dom
npm install @babel/preset-react --save-dev
Vue:
npm install vue
npm install vue-loader --save-dev
Angular: Webpack adalah bundler yang mendasari Angular CLI.
