Best practice for minimizing JavaScript in the webpack configuration file

Currently, I am following a tutorial on webpack, but it appears that the tutorial is based on an older version of webpack. I am attempting to reduce the size of the .js files, however, every time I execute npm run webpack, I encounter the following error message in the console:

webpack.optimize.UglifyJsPlugin has been removed, please use config.optimization.minimize instead.

Could someone guide me on how to implement config.optimization.minimize? I have been searching online for a solution without any luck. What changes should I make in my webpack.config.js file?

Below is my current webpack.config.js:

const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const extractCSS = new ExtractTextPlugin('allstyles.css');

module.exports = {
  entry: './wwwroot/source/app.js',
  output: {
    path: path.resolve(__dirname, 'wwwroot/dist'),
    filename: 'bundle.js'
  },
  plugins: [
    extractCSS,
    new webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery',
      'window.jQuery': 'jquery',
      Popper: ['popper.js', 'default']
    }),
    new webpack.optimize.UglifyJsPlugin()
  ],
  module: {
    rules: [
      {test: /\.css$/, use: extractCSS.extract(['css-loader?minimize'])},
      {test: /\.js$/,//      
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['env']
          }
        }
      }
    ]
  }
};

package.json:

{
  "name": "WebpackBlogExample",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "wbp": "webpack"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.3",
    "babel-preset-env": "^1.6.1",
    "bootstrap": "^4.0.0-beta.2",
    "css-loader": "^0.28.10",
    "extract-text-webpack-plugin": "^3.0.2",
    "jquery": "^3.3.1",
    "popper.js": "^1.12.9",
    "style-loader": "^0.20.2",
    "uglifyjs-webpack-plugin": "^1.2.2",
    "webpack": "^4.0.1",
    "webpack-cli": "^2.0.9"
  },
  "dependencies": {}
}

Answer №1

https://example.com/webpack-4-optimization

If you visit the provided URL, you will find detailed explanations of all optimization options for webpack 4.

During development in webpack 4, JavaScript files are not minimized by default to enhance speed. However, switching to production mode or using the -p flag while running webpack will automatically minimize your JS, eliminating the need for setting up UglifyJS in webpack 4.

Answer №2

Enhancing JavaScript Minification with Webpack 4.X

Utilizing UglifyJSPlugin:

const UglifyJSPlugin = require('uglifyjs-webpack-plugin')

...

optimization: {
  minimizer: [
    new UglifyJSPlugin({
      uglifyOptions: { ... }
    })
  ]
}

Exploring Other Options:

Although the UglifyJSPlugin is a popular choice for minifying JavaScript, there are alternative options available. Some other well-known options include:

[BabelMinifyWebpackPlugin][1]
[ClosureCompilerPlugin][1]

If you opt for a different tool, ensure that it effectively removes dead code as specified in the tree shaking guide.

source: https://webpack.js.org/guides/production/

Check out:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The functionality of linear mode seems to be malfunctioning when using separate components in the mat-horizontal-stepper

In an effort to break down the components of each step in mat-horizontal-stepper, I have included the following HTML code. <mat-horizontal-stepper [linear]="true" #stepper> <mat-step [stepControl]="selectAdvType"> <ng-template matStep ...

Methods used on a server and methods used on a client-side application

In my ASP.NET application using C# 2.0, I have created objects for a database with properties that can be called natively or through a RESTful JSON API. These objects are used to convert data into HTML for display on the website. On the site, there are se ...

transferring data between react components

I am currently working on breaking down code into smaller components, starting with the snippet below from Rows.jsx. I am struggling to grasp how props are passed between parent and child components. Despite reading several guides and articles, I remain un ...

Is there another way to retrieve a marketplace's product details using code?

When it comes to scraping products from various websites, I have discovered a clever method using window.runParams.data in the Chrome console. This allows me to easily access all the information without having to go through countless clicks to extract it f ...

What is the process for updating IDs and names for duplicated elements?

I have created a select box and used the clone function to generate dynamic select boxes. However, the cloned select boxes have the same ids and names as the original. How can I change the ids and names of the cloned elements in my code sample below: < ...

Unexpected error: JSON data at line 1 column 1 of the JSON data is incomplete

I've encountered an issue with my script related to a JSON response error. Below is the code snippet in question: $(document).ready(function() { $('#btndouble').click(function(){ var address = $('#btcaddress').val(); ...

ngSwitchCase provider not found

While following a tutorial and trying to implement what I learned, I encountered an error that I'm having trouble understanding. The browser console shows an error message stating [ERROR ->]<span *ngSwitchCase="true">, but I can't figure ...

What is the best way to accurately determine an element's location after scrolling to it?

I'm currently working on pinpointing the location of a specific element on a webpage once it has been scrolled to using JavaScript. Queries: How can I precisely determine the position of an element post-scroll? What are some common errors or extra st ...

Issue with Material-UI AppBar buttons repositioning to center of screen upon page refresh

One of the components in my project is a Material-UI AppBar, which consists of various elements such as icons and buttons. Here is the code snippet for this component: import React from 'react' import AppBar from 'material-ui/AppBar' i ...

If an AngularJS Form Item is hidden with jQuery's hide() method, will it still be validated?

Even though we're in 2020, I'm still working with AngularJS 1.x instead of the newer version due to work requirements. Despite this limitation, I am facing a challenge with setting up a form that requires exclusive-or validation between two field ...

Troubleshooting: Issues with window.location.href and window.open within an iframe

Code Update <div> <button type="button" class="submit btn btn-default" id="btnSubmit">Submit </button> <button type="button">Cancel</button> </div> <script> $("#btnSubmit").click(function(e) { ...

Utilizing the Kraken.com API to create a message signature with AngularJS

I'm currently tackling Angular2 and for my first project, I want to tap into the Kraken.com API. (I know, I could have chosen an easier task :) The "Public" calls are working smoothly, but I've hit a snag with the "Private" methods. (Those requi ...

Revamp local route variables in Express.js without the need for a page refresh

Currently, I am working on a project using node.js along with the express.js framework and EJS for template handling. Below is my routing code: app.get('/',function(req,res) { res.render('index', { matches: [], status_messag ...

VueJS - Input Image Display Issue Causing Browser Slowdown

I'm experiencing some issues with my VueJS component that includes a file input and displays an image afterwards. Strangely, this is causing my web browsers (both Firefox and Chromium) to freeze up and use massive amounts of CPU. I tried switching to ...

WebGL annotations failing to display on the webpage

I'm currently working on displaying a 3D model using Three.js in a web browser and looking to incorporate annotations like the ones shown in this Sketchfab model: Interactive 3D Test. I came across a helpful guide at this link, but I'm facing iss ...

retain focus even after using .blur()

Currently, I am implementing a form submission using AJAX. The form consists of only one input field and the submit button is hidden. My aim is to ensure that when the user hits the enter key, the input field does not lose its focus. Here's the code s ...

When a radiobutton is clicked, a jQuery call to a PHP function triggers an AJAX request which results in a JavaScript function becoming unrefer

Currently, I have a situation where two radio buttons are representing different products. When one of them is clicked, the goal is to update the price displayed on the website based on the selected product. Everything seems to be working fine when using t ...

JavaScript implementation of Ancient Egyptian Multiplication using PHP code

Let's dive into the algorithm. If we have two integers, A and B (remember, only integers), that need to be multiplied, here is how it works: we continuously multiply A by 2 and divide B by 2 until B cannot be divided any further, or in other words, un ...

Utilizing JavaScript to control the visibility of a div based on radio button selection without the need

I am facing an issue with my HTML code that is only partially working. I am attempting to display text inputs based on a radio button selection. At the moment, the code successfully hides the other options when a radio button is clicked, but upon the ini ...

Utilizing Knockout to Render JSON List Items

Utilizing Knockout.js to dynamically update a view from JSON response has been my current focus. The structure of the JSON is as follows: var data = { "Properties": { "Engine Capacity": "1499cc", "Doors": 3, "Extras": [ "LED lights", ...