'Strip long white spaces when using webpack

I have lots of white spaces in my js file, example:

 ${u} </div>\n            <div 

is there any configuration on webpack which can remove these white spaces? so output would be? maybe just convert multiple white spaces to one?

${u} </div>\n <div 

I am using Webpack 5



Solution 1:[1]

In most scenarios, the string-replace-loader should work fine. Don't forget to install it first

Example:

module.exports = {
  // ...
  module: {
    rules: [
      {
        test: sameTestAsForYourSrcFolderProbably,
        loader: 'string-replace-loader',
        options: {
          // replace multiple non-indent spaces with a single space
          search: /(?<!\n\s*)[ ]+/,
          replace: ' ',
        }
      }
    ]
  }
}

The search option takes a regex. It looks so complicated because it contains a negative lookbehind to prevent it from gobbling up indentation (that is any whitespace following a new line \n).

Good luck!

Solution 2:[2]

If you are in fact using Webpack 5 and see whitespaces in your compiled javascript code, I believe you have some faulty setting in your webpack.config file. By default webpack 5 both minifies and strip white-spaces/returns etc. Only exception is within resources or special string values such as what styled components create. However, the latter is easily compressed by gzip.

Have you tried running a build without a config to see what bundle it creates for you?

yarn webpack --mode production

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Joakim Poromaa Helger