DEV Community

Cover image for Webpack Cheatsheet
Arjun Porwal
Arjun Porwal

Posted on

Webpack Cheatsheet

Table Of Contents

Webpack Cheatsheet


Webpack Cheatsheet

Link to an Awesome Webpack Boilerplate : Athlon Webpack boilerplate

Collection of all my sheets are at Github

Installation

npm install webpack webpack-cli --save-dev
Enter fullscreen mode Exit fullscreen mode
//webpack.config.js
const path = require("path");

module.exports = {
   entry: "./src/index.js",
   output: {
      filename: "bundle.js",
      path: path.resolve(__dirname, "./dist"),
   },
   mode: "none",
};
Enter fullscreen mode Exit fullscreen mode

using Webpack , we can now export and import data and files between each other.


Loaders

Libraries that help to import stuff using webpack

Adding Images

npm install file-loader --save-dev
Enter fullscreen mode Exit fullscreen mode
//webpack.config.js
module.exports = {
   entry: "./src/index.js",
   output: {
      filename: "bundle.js",
      path: path.resolve(__dirname, "./dist"),
      publicPath: "", /* to specify image location for html , website URL in production */
   },
   mode: "none",
   module: {
      rules: [
         {
            test: /\.(png|jpg)$/,
            use: ["file-loader"],
         },
      ],
   },
};
Enter fullscreen mode Exit fullscreen mode
//index.js
import Kiwi from "./kiwi.jpg";
Enter fullscreen mode Exit fullscreen mode

Adding CSS in JS

npm install style-loader css-loader --save-dev
Enter fullscreen mode Exit fullscreen mode
//webpack.config.js
{
    test: /\.css$/,
    use: ["style-loader", "css-loader"],
},
Enter fullscreen mode Exit fullscreen mode
//component.js
import "./hello-world-button.css";
Enter fullscreen mode Exit fullscreen mode

Adding SCSS

npm install sass-loader sass --save-dev
Enter fullscreen mode Exit fullscreen mode
//webpack.config.js
{
    test: /\.scss$/,
    use: ["style-loader", "css-loader", "sass-loader"], //first style-loader at last sass-loader
},
Enter fullscreen mode Exit fullscreen mode
//component.js
import "./hello-world-button.scss";
Enter fullscreen mode Exit fullscreen mode

Adding Babel

npm install @babel/core babel-loader @babel/preset-env babel-plugin-transform-class-properties --save-dev
Enter fullscreen mode Exit fullscreen mode
//webpack.config.js
{
    test: /\.js$/,
    exclude: /node_modules/,
    use: {
        loader: "babel-loader",
        options: {
            presets: ["@babel/env"],
            plugins: ["transform-class-properties"],
        },
    },
},
Enter fullscreen mode Exit fullscreen mode

Plugins

Plugins Perform Specific Actions on the Imported Stuff

Minify JS

npm install terser-webpack-plugin --save-dev
Enter fullscreen mode Exit fullscreen mode
//webpack.config.js
const TerserPlugin = require("terser-webpack-plugin");

/* Inside Module.exports */
plugins: [new TerserPlugin()],
Enter fullscreen mode Exit fullscreen mode

Extracting CSS into a Specific File

npm install mini-css-extract-plugin --save-dev
Enter fullscreen mode Exit fullscreen mode
//webpack.config.js
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
    rules = [
        {
            test: /\.css$/,
            use: [MiniCssExtractPlugin.loader, "css-loader"],
        },
        {
            test: /\.scss$/,
            use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"],
        },
    ]
}

plugins: [
    new MiniCssExtractPlugin({
        filename: "style.css",
    }),
],
Enter fullscreen mode Exit fullscreen mode

Generate New File Name Every Execution (only on content change)

//simple add [contenthash] to the filename you want to have new name
filename: "bundle.[contenthash].js",
Enter fullscreen mode Exit fullscreen mode

Deleting Old Files and Rendering new on Every Build

npm install clean-webpack-plugin --save-dev
Enter fullscreen mode Exit fullscreen mode
//webpack.config.js

const { CleanWebpackPlugin } = require("clean-webpack-plugin");

// Running This PLugin without option , will automatically clean dist folder

plugins: [
    new CleanWebpackPlugin({
        cleanOnceBeforeBuildPatterns: [
            "**/*",  //this runs by default in dist folder
            path.join(process.cwd(), "build/**/*"), //adding other folders
        ],
    }),
],
Enter fullscreen mode Exit fullscreen mode

Generating HTML using Webpack

npm install html-webpack-plugin --save-dev 
Enter fullscreen mode Exit fullscreen mode
//webpack.config.js

const HtmlWebpackPlugin = require("html-webpack-plugin");

plugins: [
    new HtmlWebpackPlugin(), //generates default html file
]

//publicPath can be empty as html is generated in the same place as other files by default. (the path specified)
Enter fullscreen mode Exit fullscreen mode

- Specifying Manual HTML options

new HtmlWebpackPlugin({  //extra options for the html file
    title: "Hello World",
    filename: "subfolder/custom_filename.html",
    meta: {
        description: "Some Description",
    },
}),
Enter fullscreen mode Exit fullscreen mode

- Using HTML template Engine (HandleBars)

npm install handlebars-loader --save-dev
npm install handlebars --save
Enter fullscreen mode Exit fullscreen mode
// Add a Test in module rules for hbs files to use handlebars loader
{
    test: /\.hbs$/,
    use: ["handlebars-loader"],
}

//Also add the new plugin to access hbs
new HtmlWebpackPlugin({
    title: "Hello World",
    template: "src/index.hbs",
    description: "Some Description",
}),
Enter fullscreen mode Exit fullscreen mode

Development and Production Builds

Changing Mode

//webpack.config.js
module.exports = {
    mode : "production", //for production (here no source or anything is done)
    mode : "development", //source maps are rendered and development is faster
    mode : "none" //to not use any mode
}
Enter fullscreen mode Exit fullscreen mode

Creating Different Config for Different Modes

  • Save Your Webpack configuration in different files , changing the mode specifically in both
  • then create the npm scripts for specific files
//package.json

"scripts": {
    "build": "webpack --config webpack.production.config.js",
    "dev": "webpack --config webpack.dev.config.js"
  },
Enter fullscreen mode Exit fullscreen mode

Using Webpack-dev-server in Development mode

npm install webpack-dev-server --save-dev
Enter fullscreen mode Exit fullscreen mode
//webpack.dev.config.js

module.exports = {
    devServer: {
         contentBase : path.resolve(__dirname, "./dist"),
         index: 'index.html',
         port: 9000
   }
}
Enter fullscreen mode Exit fullscreen mode
//package.json

scripts = {
    "dev": "webpack-dev-server --config webpack.dev.config.js --hot"
}
Enter fullscreen mode Exit fullscreen mode

Multi Page Applications

Rendering Multiple Pages

//webpack.production.config.js

module.exports = {
    entry: {
        'hello-world': './src/hello-world.js', //file 1
        'kiwi': './src/kiwi.js', // file 2
    },
    output: {
        filename: "[name].[contenthash].js", //will generate different names
        path: path.resolve(__dirname, "./dist"),
        publicPath: "",
    },
    plugins: [
        new MiniCssExtractPlugin({
            filename: "[name].[contenthash].css", //same for css files
        }),
        new HtmlWebpackPlugin({
         filename: 'hello-world.html', //different Html Files
         chunks: ['hello-world'], //is used from entry point
         title: "Hello World",
         description: "Hello World",
         template: "src/page-template.hbs",
      }),
      new HtmlWebpackPlugin({
         filename: 'kiwi.html',
         chunks: ['kiwi'], //specify only the ones u need
         title: "Kiwi",
         description: "Kiwi",
         template: "src/page-template.hbs",
      }),
    ]
}
Enter fullscreen mode Exit fullscreen mode

Creating Common File for Dependencies

//webpack.production.config.js

module.exports = {
    optimization: {
        splitChunks: {
            chunks: "all", //this will integrate all the extra packages into one extra js file 
            minSize : 10000, //this specifies the minimum size of the bundle to split
             automaticNameDelimiter: '_' //this specifies the separation between file names , by default ~
        }
    },  
    plugins : [
        new HtmlWebpackPlugin({
            chunks: ['hello-world'],
        }),
        new HtmlWebpackPlugin({
            chunks: ['kiwi'],
        }),
    ] // integrating the extra modules js file into the HTML 

}
Enter fullscreen mode Exit fullscreen mode

Extras

Adding Custom Fonts

//webpack.config.js
{
    test: /\.{woff2|woff}$/,
    use: [
        {
            loader: 'file-loader',
            options: {
                name: '[name].[ext]',
                outputPath: 'fonts/',
            }
        }
    ],
}

//add font face in scss 
//import scss in js
Enter fullscreen mode Exit fullscreen mode

Adding Bootstrap

npm install bootstrap jquery popper.js --save
Enter fullscreen mode Exit fullscreen mode
  • Use Bootstrap , without editing it
import "bootstrap";
import "bootstrap/dist/css/bootstrap.min.css";
Enter fullscreen mode Exit fullscreen mode
  • Use Precompiled Bootstrap
npm install postcss-loader precss autoprefixer --save-dev
Enter fullscreen mode Exit fullscreen mode
//webpack.config.js

test: /\.scss$/,
    use: [
        MiniCssExtractPlugin.loader,
        "css-loader",
        {
            loader: "postcss-loader",
            options: {
                plugins: function () {
                    return [require("precss"), require("autoprefixer")];
                },
            },
        },
        "sass-loader",
    ],
Enter fullscreen mode Exit fullscreen mode
//index.scss
@import "~bootstrap/scss/bootstrap";
Enter fullscreen mode Exit fullscreen mode

Adding Font Awesome

  • Installing Core packages to only include needed icons in final bundle
npm install --save-dev @fortawesome/fontawesome-svg-core @fortawesome/free-solid-svg-icons @fortawesome/free-regular-svg-icons @fortawesome/free-brands-svg-icons
Enter fullscreen mode Exit fullscreen mode
//index.js

import { library, dom } from "@fortawesome/fontawesome-svg-core";
//library is used to import the specific icon , dom replaces i tag in DOM
import { faSpinner } from "@fortawesome/free-solid-svg-icons";
// import only the icons needed 


library.add(faSpinner); //puts the icon in the library
dom.watch(); //watches for changes in the html, and replaces every font awesome <i> tag
Enter fullscreen mode Exit fullscreen mode
<!-- index.html -->

<i class="fas fa-spinner fa-spin"></i> 
<!-- simply consume the icon needed -->
Enter fullscreen mode Exit fullscreen mode

ES Lint

  • This file specifies basic rules to check for errors in js , especially used for linting and providing universal using standard.
npm install eslint babel-eslint --save-dev
Enter fullscreen mode Exit fullscreen mode
  • create .eslintrc.json (can be generated too , check out docs)
{
    "extends": "eslint:recommended", //recommended settings
    "parser": "babel-eslint", // babel for classes
    "parserOptions": { //for es6 import and others
        "ecmaVersion": 6,
        "sourceType": "module"
    }, 
    "env": {
        "node": true, //tells we are using node , for "require"
        "browser": true //tells running in browser , for "document"
    },
    "rules": { //specific rules that we want to add
        "no-console": 0
    }
}
Enter fullscreen mode Exit fullscreen mode
  • manually run eslint using eslint .
  • or Install specific Linter plugins in your Editor to get the errors while coding itself.

Top comments (0)