Webpack

this doc is meant to explain webpack briefly if you want to learn more visit the official website of webpack

How To use

to implement webpack you can use webpack init in your terminal, and then webpack will be automatically created in your project but before that, you need to install some library from webpack

Run in your terminal

// need to install first
npm i -g webpack-cli
npm i -g webpack
// and then
webpack init

after run webpack init you can setup what you want for example this is my default setup

if the response asks you to overwrite your package.json, I suggest answering with no,and then change your "scripts' in package.json to be like this only scripts key

  "scripts": {
    "build": "webpack --mode=production --node-env=production",
    "build:dev": "webpack --mode=development",
    "build:prod": "webpack --mode=production --node-env=production",
    "watch": "webpack --watch",
    "serve": "webpack serve"
  },

Open your webpack.config.js

maybe your webpack.config.js file will be like this

// Generated using webpack-cli https://github.com/webpack/webpack-cli

const path = require('path');

const isProduction = process.env.NODE_ENV == 'production';


const config = {
    entry: './src/index.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
    },
    devServer: {
        open: true,
        host: 'localhost',
    },
    plugins: [
        // Add your plugins here
        // Learn more about plugins from https://webpack.js.org/configuration/plugins/
    ],
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/i,
                loader: 'babel-loader',
            },
            {
                test: /\.(eot|svg|ttf|woff|woff2|png|jpg|gif)$/i,
                type: 'asset',
            },

            // Add your rules for custom modules here
            // Learn more about loaders from https://webpack.js.org/loaders/
        ],
    },
};

module.exports = () => {
    if (isProduction) {
        config.mode = 'production';
        
        
    } else {
        config.mode = 'development';
    }
    return config;
};

The Structure

Entry

The entry inside config signifies the entry point of the application.

Output

The top-level output key contains a set of options instructing webpack on how and where it should output your bundles, assets, and anything else you bundle or load with webpack.

devServer

devserver is used for settings in development mode, for example you can choose the port you want

Plugins

plugins is used for example the community develops plugins for webpack and webpack doesn't support it yet for example a plugin to remove all consoles, `TerserPlugin` is one of the plugins that you need to add if you want to remove all console.log from your code

Modules

Module. rules allow you to specify several loaders within your webpack configuration. This is a concise way to display loaders, and helps to maintain clean code. It also offers you a complete overview of each respective loader for example only js and jsx files read as code

Addtional

You can customize where behavior in dev and production has some differences

Real Project Implentation

in the docial project we use webpack to wrap the application and make it into a smaller bundle file,and then as you can see we have 3 file webpack.config.js,webpack.dev.js,webpack.prod.js,

Webpack.config.js

this file is used to set up the webpack which will be used in prod and development, the point is that when prod and dev have something in common we can write it here like the config variable above

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const webpack = require('webpack')

module.exports = {
  entry: './src/index.js',
  module: {
    rules: [
      {
        test: /\.(png|jpe?g|gif|mp4)$/i,
        use: [
          {
            loader: 'file-loader',
          },
        ],
      },
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      },
    ],
  },
  output: {
    publicPath: "/",
    path: path.resolve(__dirname, "dist"),
    filename: "bundle.js"
},
  resolve: {
    extensions: ['.js', '.jsx'],

  },
  performance: {
    hints: false,
    maxEntrypointSize: 512000,
    maxAssetSize: 512000
},
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin,
    new HtmlWebpackPlugin({
      filename: 'index.html',
      manifest: './public/manifest.json',
      favicon: './public/ic_dc.png',
      template: path.join(__dirname, '/public/index.html'),
    }),
  ],
 
}

Webpack.dev.js

used and run only in dev mode

{ merge } = require('webpack-merge');
const common = require('./webpack.config.js');
const path = require('path')
module.exports = merge(common, {
    mode: 'development',
    devtool: 'source-map',
    devServer: {
        compress: true,
        historyApiFallback: true,
        port: 3030,
        hot: true
    },
    output: {
        filename: '[name].bundle.js',
        path: path.resolve(__dirname, 'public'),
        publicPath: '/',
        clean: true,
    },
});

Webpack.prod.js

used and run only in production mode

const { merge } = require('webpack-merge');
const path = require('path')
const common = require('./webpack.config.js');
const TerserPlugin = require("terser-webpack-plugin");

module.exports = merge(common, {
    mode: 'production',
    devtool: 'source-map',
    devServer: {
        hot: true,
        open: true,
        historyApiFallback: true,
        port: 3000,
        static: './dist',
    },
    output: {
        filename: '[name].bundle.js',
        path: path.resolve(__dirname, 'dist'),
        publicPath: '/',
        clean: true,
    },
    stats: { warnings: false },
    optimization: {
        minimize: true,
        minimizer: [
            new TerserPlugin({
                terserOptions: {
                    compress: {
                        drop_console: true,
                    },
                },
            }),
        ],
    },
});

and then you can change some code in your package.json file like this one

  "scripts": {
    "start-webpack": "webpack serve --open --config ./webpack.dev.js",// to run as dev in local serv
    "start-webpack-prod": "webpack serve --open --config ./webpack.prod.js",//to run prod bunlde in your local serve
    "build-webpack": "webpack --config ./webpack.prod.js",//to build bundle file
  },

Last updated

Was this helpful?