DEV Community

Cover image for Popular React Webpack Plugins for 2022
Shivam Pawar
Shivam Pawar

Posted on

Popular React Webpack Plugins for 2022

Use the right tool, for the right job, in the right way

If we have right tools available, development become a easier. In this post I’ll discuss some popular webpack plugins which are mostly used for production ready React.js application build process.

This article is extended part of my previous blog post.

If you want to know about Webpack and it’s configuration with react application in simple steps, you can read Setup Webpack and Babel for a React.Js Application.

Here are the plugins which I personally use for my React Application:

Webpack Dashboard

Default webpack build process output looks like this:

build_before

Above output is difficult to read and understand. Also information is not well formatted and presented.

Here webpack dashboard come in picture to have a better visual of output. Install it by typing command in cmd.

npm install --save-dev webpack-dashboard
Enter fullscreen mode Exit fullscreen mode

Note: webpack-dashboard@^3.0.0 requires Node 8 or above. Previous versions support down to Node 6.

Now, We need to import this plugin in webpack.config.js and add in plugins array.

//webpack.config.js

const path = require('path');
const webpackDashboard = require('webpack-dashboard/plugin');
module.exports = {
   entry: './src/index.js',
   output: {
      path: path.join(__dirname, '/dist'),
      filename: 'bundle.js'
   },
   devServer: {
      port: 8080
   },
   module: {
      rules: [
         {
            test: /\.jsx?$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
         },
         {
            test: /\.css$/,
            use: [ 'style-loader', 'css-loader' ]
        }
      ]
   },
   plugins:[
       new webpackDashboard()
   ]
}
Enter fullscreen mode Exit fullscreen mode

Also need to modify your script in package.json. Just need to append webpack-dashboard β€” before every script. And its all done!

"scripts": {
    "start": "webpack-dashboard -- webpack serve --mode development --open --hot",
    "build": "webpack-dashboard -- webpack --mode production"
  }
Enter fullscreen mode Exit fullscreen mode

Run your application and you will see a fantastic build process output.😍

after-build

Terser Webpack Plugin

The terser webpack plugin is used to compress the size of your JavaScript bundle for production use. Also this plugin support ES6+ modern JavaScript syntax.

Note: Terser webpack plugin by default comes with webpack 5. This plugin will only needed when your webpack version is lower than 5.

Install this plugin using below command:

npm install --save-dev terser-webpack-plugin
Enter fullscreen mode Exit fullscreen mode

Then import and add this plugin to your webpack.config.js.

//webpack.config.js

const path = require('path');
const webpackDashboard = require('webpack-dashboard/plugin');
const TerserPlugin = require("terser-webpack-plugin");

module.exports = {
   entry: './src/index.js',
   output: {
      path: path.join(__dirname, '/dist'),
      filename: 'bundle.js'
   },
   optimization: {
      minimize: true,
      minimizer: [new TerserPlugin()],
    },
   devServer: {
      port: 8080
   },
   module: {
      rules: [
         {
            test: /\.jsx?$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
         },
         {
            test: /\.css$/,
            use: [ 'style-loader', 'css-loader' ]
        }
      ]
   },
   plugins:[
       new webpackDashboard()
   ]
}
Enter fullscreen mode Exit fullscreen mode

There are lots of options available with this plugin which you can check here.

Optimize CSS Assets Webpack Plugin

This plugin will search for all CSS files in your project and optimize / minify the CSS.

Install this plugin using:

npm install --save-dev optimize-css-assets-webpack-plugin mini-css-extract-plugin css-loader
Enter fullscreen mode Exit fullscreen mode

Import and add this plugin in webpack.config.js.

//webpack.config.js

const path = require('path');
const TerserPlugin = require("terser-webpack-plugin");
const webpackDashboard = require('webpack-dashboard/plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = {
   entry: './src/index.js',
   output: {
      path: path.join(__dirname, '/dist'),
      filename: 'bundle.js'
   },
   optimization: {
      minimize: true,
      minimizer: [new TerserPlugin(), new MiniCssExtractPlugin()],
    },
   devServer: {
      port: 8080
   },
   module: {
      rules: [
         {
            test: /\.jsx?$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
         },
         {
            test: /\.css$/i,
            use: [MiniCssExtractPlugin.loader, 'css-loader'],
         }, 
      ]
   },
   plugins:[
       new webpackDashboard(),
       new MiniCssExtractPlugin(),
       new OptimizeCssAssetsPlugin({
         assetNameRegExp: /\.optimize\.css$/g,
         cssProcessor: require('cssnano'),
         cssProcessorPluginOptions: {
           preset: ['default', { discardComments: { removeAll: true } }],
         },
         canPrint: true
       })
   ]
}
Enter fullscreen mode Exit fullscreen mode

You can read more about Optimize CSS assets Webpack Plugin here.

HTML Webpack Plugin

HTML webpack plugin is used to generate HTML file and inject a script tag with JavaScript code. This plugin is used for both development and production build.

Install this plugin using:

npm install --save-dev html-webpack-plugin
Enter fullscreen mode Exit fullscreen mode

Import and add this plugin in webpack.config.js as:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const TerserPlugin = require("terser-webpack-plugin");
const webpackDashboard = require('webpack-dashboard/plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');


module.exports = {
   entry: './src/index.js',
   output: {
      path: path.join(__dirname, '/dist'),
      filename: 'bundle.js'
   },
   optimization: {
      minimize: true,
      minimizer: [new TerserPlugin(), new MiniCssExtractPlugin()],
    },
   devServer: {
      port: 8080
   },
   module: {
      rules: [
         {
            test: /\.jsx?$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
         },
       {
         test: /\.css$/i,
         use: [MiniCssExtractPlugin.loader, 'css-loader'],
     }, 
      ]
   },
   plugins:[
       new HtmlWebpackPlugin(
         Object.assign(
           {},
           {
             inject: true,
             template: path.join(__dirname,'/src/index.html')
           },

           // Only for production
           process.env.NODE_ENV === "production" ? {
             minify: {
               removeComments: true,
               collapseWhitespace: true,
               removeRedundantAttributes: true,
               useShortDoctype: true,
               removeEmptyAttributes: true,
               removeStyleLinkTypeAttributes: true,
               keepClosingSlash: true,
               minifyJS: true,
               minifyCSS: true,
               minifyURLs: true
             }
           } : undefined
         )
       ),
       new webpackDashboard(),
       new MiniCssExtractPlugin(),
       new OptimizeCssAssetsPlugin({
         assetNameRegExp: /\.optimize\.css$/g,
         cssProcessor: require('cssnano'),
         cssProcessorPluginOptions: {
           preset: ['default', { discardComments: { removeAll: true } }],
         },
         canPrint: true
       })
   ]
}
Enter fullscreen mode Exit fullscreen mode

You can read more about options provided by html-webpack-plugin here.

Clean Webpack Plugin

Clean webpack plugin is used to clean / remove your build folder. It will also remove all unused webpack assets after every successful rebuild.

This plugin will help to reduce the bundle size by removing unwanted files and assets from production ready folder.

Install this plugin using:

npm install --save-dev clean-webpack-plugin
Enter fullscreen mode Exit fullscreen mode

Import and add this plugin in your webpack.config.js as:

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const TerserPlugin = require("terser-webpack-plugin");
const webpackDashboard = require("webpack-dashboard/plugin");
const OptimizeCssAssetsPlugin = require("optimize-css-assets-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");

module.exports = {
  entry: "./src/index.js",
  output: {
    path: path.join(__dirname, "/dist"),
    filename: "bundle.js",
  },
  optimization: {
    minimize: true,
    minimizer: [new TerserPlugin(), new MiniCssExtractPlugin()],
  },
  devServer: {
    port: 8080,
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: "babel-loader",
      },
      {
        test: /\.css$/i,
        use: [MiniCssExtractPlugin.loader, "css-loader"],
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin(
      Object.assign(
        {},
        {
          inject: true,
          template: path.join(__dirname, "/src/index.html"),
        },

        // Only for production
        process.env.NODE_ENV === "production"
          ? {
              minify: {
                removeComments: true,
                collapseWhitespace: true,
                removeRedundantAttributes: true,
                useShortDoctype: true,
                removeEmptyAttributes: true,
                removeStyleLinkTypeAttributes: true,
                keepClosingSlash: true,
                minifyJS: true,
                minifyCSS: true,
                minifyURLs: true,
              },
            }
          : undefined
      )
    ),
    new webpackDashboard(),
    new MiniCssExtractPlugin(),
    new OptimizeCssAssetsPlugin({
      assetNameRegExp: /\.optimize\.css$/g,
      cssProcessor: require("cssnano"),
      cssProcessorPluginOptions: {
        preset: ["default", { discardComments: { removeAll: true } }],
      },
      canPrint: true,
    }),
    new CleanWebpackPlugin({
      // Use !negative patterns to exclude files
      // default: []
      cleanAfterEveryBuildPatterns: ["static*.*", "!static1.js"],

      // Write Logs to Console
      // (Always enabled when dry is true)
      // default: false
      verbose: true,
    }),
  ],
};
Enter fullscreen mode Exit fullscreen mode

clean

You can see after running npm run build, all files under dist folder get removed and after that only required files get emitted and temp.js is get removed as it has no reference in any files.

Thanks for reading this blog post. Feel free to comment in comment box if you face any problem while configuring these plugins with webpack.

If you found this article useful, please share it with your friends and colleagues!❀️

Read more articles on Dev.To ➑️ Shivam Pawar

Follow me on ‡️
🌐 LinkedIn
🌐 Github

Top comments (1)

Collapse
 
wkylin profile image
Info Comment hidden by post author - thread only accessible via permalink
wkylin.w

Some comments have been hidden by the post's author - find out more