Here’s a beginner-friendly guide to Webpack Basics — perfect for understanding how it helps bundle and manage your web development assets.
📦 What is Webpack?
Webpack is a powerful module bundler for JavaScript applications.
It bundles all your JS, CSS, images, and other files into optimized files for the browser.
💡 Why Use Webpack?
Benefit | Description |
---|---|
🔗 Module bundling | Combines many JS modules into one or more optimized bundles |
📦 Asset management | Handles CSS, images, fonts, etc. |
⚡ Performance | Tree-shaking, code splitting, caching |
🔁 Dev convenience | Live reloading, hot module replacement |
🔐 Production-ready | Minifies & compresses assets |
📁 Typical Project Structure
lua
my-app/
├── src/
│ ├── index.js
│ └── style.css
├── dist/
├── package.json
├── webpack.config.js
🔧 Webpack Core Concepts
Concept | Purpose |
---|---|
Entry | Where Webpack starts (your main JS file) |
Output | Where bundled files are saved |
Loaders | Transform files (like SCSS, images, etc.) |
Plugins | Extend Webpack’s functionality |
Mode | development or production |
📄 Basic webpack.config.js
js
const path = require('path');
module.exports = {
entry: './src/index.js', // Start point
output: {
filename: 'bundle.js', // Output bundle
path: path.resolve(__dirname, 'dist'),
},
mode: 'development', // or 'production'
module: {
rules: [
{
test: /\.css$/, // Handle CSS files
use: ['style-loader', 'css-loader'],
},
],
},
};
📦 Installing Webpack
bash
npm init -y
npm install webpack webpack-cli --save-dev
Then run:
bash
npx webpack
Creates dist/bundle.js
.
🔁 Live Development with Webpack Dev Server
bash
npm install webpack-dev-server --save-dev
Add this script in package.json
:
json
"scripts": {
"start": "webpack serve --open"
}
Run:
bash
npm run start
✅ Automatically rebuilds and reloads your app.
⚙️ Useful Loaders
Loader | For |
---|---|
babel-loader | Transpile JS (ES6+) |
css-loader | Load CSS files |
style-loader | Inject CSS into DOM |
sass-loader | Use SCSS/SASS |
file-loader | Load images/fonts |
url-loader | Inline small assets |
🔌 Popular Plugins
Plugin | Purpose |
---|---|
HtmlWebpackPlugin | Generate index.html with script injected |
MiniCssExtractPlugin | Extract CSS into separate files |
CleanWebpackPlugin | Clean output folder before building |
DefinePlugin | Define global constants |
✨ Bonus: Tree Shaking & Code Splitting
Tree shaking: Remove unused code
Code splitting: Break code into smaller chunks that load only when needed
js
import(/* webpackChunkName: "lodash" */ 'lodash').then(_ => {
// dynamic import (code split)
});
✅ Summary
Feature | Webpack |
---|---|
Role | Module bundler |
Entry Point | entry: in config |
Output | Compiled bundle.js |
Loaders | Handle non-JS files |
Plugins | Automate and optimize build |
Dev Server | Auto rebuild + reload |