What is Webpack?

  • Webpack is a module bundler for JavaScript applications.

  • It takes your JavaScript files (and other assets like CSS, images) and bundles them into one or more optimized files for the browser.

  • Helps manage dependencies and improve performance.


Why Use Webpack?

  • Bundles multiple files into fewer files (often one).

  • Supports modern JavaScript features (ES6 modules).

  • Allows use of loaders to process files (e.g., transpile JSX, SCSS).

  • Supports plugins to optimize build (e.g., minification, environment variables).

  • Enables hot module replacement (HMR) for fast development.


Basic Concepts

Concept Description
Entry The starting point(s) for bundling
Output Where the bundled files will be saved
Loaders Transform files (e.g., Babel for JSX)
Plugins Extend functionality (e.g., clean build folder)
Mode ‘development’ or ‘production’ optimizations

Basic Webpack Configuration Example

js
// webpack.config.js
const path = require('path');

module.exports = {
entry: './src/index.js', // Entry file
output: {
filename: 'bundle.js', // Output bundle file
path: path.resolve(__dirname, 'dist'),
},
mode: 'development', // or 'production'
module: {
rules: [
{
test: /\.js$/, // Apply loader to .js files
exclude: /node_modules/,
use: 'babel-loader', // Transpile ES6+ and JSX
},
{
test: /\.css$/, // Load CSS files
use: ['style-loader', 'css-loader'],
},
],
},
};


Running Webpack

  • Install dependencies:

bash
npm install --save-dev webpack webpack-cli babel-loader @babel/core @babel/preset-env @babel/preset-react style-loader css-loader
  • Add a build script in package.json:

json
"scripts": {
"build": "webpack"
}
  • Run build:

bash
npm run build

Summary

  • Webpack bundles your JS (and assets) into optimized files.

  • Entry point is where bundling starts.

  • Loaders transform files during bundling.

  • Plugins add extra capabilities.

  • Mode controls optimizations for dev or production.

Leave a Reply

Your email address will not be published. Required fields are marked *