Introduction to Webpack by senpai codes
04.10.2020

1- We start by testing our current environment by the following commands

$ npm -v
$ node -v

my system specifications

  • OS ubuntu 20.04
  • node version v12.18.0
  • npm version 6.14.8

2- Initialize our project

$ cd ~/Desktop/
$ mkdir webpack-intro
$ cd webpack-intro/
$ npm init -y

we endup having this new file in our project directroy “~/Desktop/webpack-intro/package.json”

{
  "name": "webpack-intro",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

3- Initialize our project structure

webpack-intro
|-- package.json
|-- index.html
|-- webpack.config.js
`-- src
  |-- main.js
  `-- style.css

4- Update project dependencies

{
  "name": "webpack-intro",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build:development": "npx webpack --mode=development",
    "build:production": "npx webpack --mode=production",
    "start": "npx webpack --watch"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@fortawesome/fontawesome-free": "^5.15.1",
    "bootstrap": "^4.5.2",
    "jquery": "^3.5.1",
    "popper.js": "^1.16.1",
    "sweetalert2": "^10.3.5"
  },
  "devDependencies": {
    "clean-webpack-plugin": "^3.0.0",
    "css-loader": "^3.2.0",
    "file-loader": "^4.3.0",
    "mini-css-extract-plugin": "^0.8.0",
    "optimize-css-assets-webpack-plugin": "^5.0.3",
    "sass": "^1.26.12",
    "sass-loader": "^10.0.2",
    "terser-webpack-plugin": "latest",
    "webpack": "^4.44.2",
    "webpack-assets-manifest": "^3.1.1",
    "webpack-cli": "^3.3.9",
    "webpack-manifest-plugin": "^2.0.4"
  }

5- Install dependencies

$ npm install

6- set Webpack config file

const path = require('path');
const webpack = require('webpack');
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
const ManifestPlugin = require('webpack-manifest-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const TerserJSPlugin = require('terser-webpack-plugin');

module.exports = (env, options) => {
    let mode = options.mode;
    console.log(`This is the Webpack 4 'mode': ${mode}`);

    //watch case
    if (mode=='undefined') {
        mode='development'
    }

    return {
    entry: {
        "main/index": path.resolve(__dirname, 'src','main.js')
    },
    output: {
      path: path.resolve(__dirname, 'dist'),
      filename: (mode=='production')?'[name].min.js':'[name].js'
    },
    optimization: {
        minimizer: [new TerserJSPlugin({}), new OptimizeCSSAssetsPlugin({})],
    },
    performance: {
        maxEntrypointSize: 1024000,
        maxAssetSize: 1024000
    },
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [MiniCssExtractPlugin.loader, 'css-loader']
            },
            {
                test: /\.(ttf|eot|svg|woff|woff2)(\?[\s\S]+)?$/,
                include: path.resolve(__dirname, './node_modules/@fortawesome/fontawesome-free/webfonts'),
                use: {
                    loader: 'file-loader',
                    options: {
                        name: '[name].[ext]',
                        outputPath: 'webfonts',
                        publicPath: '../webfonts',
                    },
                }
            },
        ],
    },
    plugins: [
        new CleanWebpackPlugin(),
        new ManifestPlugin(),
        new MiniCssExtractPlugin({
            filename: (mode=='production')?'[name].min.css':'[name].css',
            ignoreOrder: false
        }),
    ],
    watchOptions: {
        ignored: ['./node_modules/']
    },
    mode: "development" //development, production or none
  };
}

7- Run Webpack

$ npm run build:development

8- Set dummy index.html and point it the result of Webpack

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Webpack starter</title>
    <link rel="stylesheet" href="dist/main/index.css">
</head>
<body>
    <script src="dist/main/index.js"></script>
</body>
</html>

9- View the result using live server