Git Product home page Git Product logo

css-minimizer-webpack-plugin's Introduction

npm node tests cover discussion size

css-minimizer-webpack-plugin

This plugin uses cssnano to optimize and minify your CSS.

Just like optimize-css-assets-webpack-plugin but more accurate with source maps and assets using query string, allows caching and works in parallel mode.

Getting Started

To begin, you'll need to install css-minimizer-webpack-plugin:

npm install css-minimizer-webpack-plugin --save-dev

or

yarn add -D css-minimizer-webpack-plugin

or

pnpm add -D css-minimizer-webpack-plugin

Then add the plugin to your webpack configuration. For example:

webpack.config.js

const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");

module.exports = {
  module: {
    rules: [
      {
        test: /.s?css$/,
        use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"],
      },
    ],
  },
  optimization: {
    minimizer: [
      // For webpack@5 you can use the `...` syntax to extend existing minimizers (i.e. `terser-webpack-plugin`), uncomment the next line
      // `...`,
      new CssMinimizerPlugin(),
    ],
  },
  plugins: [new MiniCssExtractPlugin()],
};

This will enable CSS optimization only in production mode.

If you want to run it also in development set the optimization.minimize option to true:

webpack.config.js

// [...]
module.exports = {
  optimization: {
    // [...]
    minimize: true,
  },
};

And run webpack via your preferred method.

Note about source maps

Works only with source-map, inline-source-map, hidden-source-map and nosources-source-map values for the devtool option.

Why? Because CSS support only these source map types.

The plugin respect the devtool and using the SourceMapDevToolPlugin plugin. Using supported devtool values enable source map generation. Using SourceMapDevToolPlugin with enabled the columns option enables source map generation.

Use source maps to map error message locations to modules (this slows down the compilation). If you use your own minify function please read the minify section for handling source maps correctly.

Options

Name Type Default Description
test String|RegExp|Array<String|RegExp> /\.css(\?.*)?$/i Test to match files against.
include String|RegExp|Array<String|RegExp> undefined Files to include.
exclude String|RegExp|Array<String|RegExp> undefined Files to exclude.
parallel Boolean|Number true Enable/disable multi-process parallel running.
minify Function|Array<Function> CssMinimizerPlugin.cssnanoMinify Allows to override default minify function.
minimizerOptions Object|Array<Object> { preset: 'default' } Cssnano optimisations options.
warningsFilter Function<(warning, file, source) -> Boolean> () => true Allow to filter css-minimizer warnings.

test

Type: String|RegExp|Array<String|RegExp> - default: /\.css(\?.*)?$/i

Test to match files against.

module.exports = {
  optimization: {
    minimize: true,
    minimizer: [
      new CssMinimizerPlugin({
        test: /\.foo\.css$/i,
      }),
    ],
  },
};

include

Type: String|RegExp|Array<String|RegExp> Default: undefined

Files to include.

webpack.config.js

module.exports = {
  optimization: {
    minimize: true,
    minimizer: [
      new CssMinimizerPlugin({
        include: /\/includes/,
      }),
    ],
  },
};

exclude

Type: String|RegExp|Array<String|RegExp> Default: undefined

Files to exclude.

webpack.config.js

module.exports = {
  optimization: {
    minimize: true,
    minimizer: [
      new CssMinimizerPlugin({
        exclude: /\/excludes/,
      }),
    ],
  },
};

parallel

Type: Boolean|Number Default: true

Use multi-process parallel running to improve the build speed. Default number of concurrent runs: os.cpus().length - 1.

ℹ️ Parallelization can speed up your build significantly and is therefore highly recommended. If a parallelization is enabled, the packages in minimizerOptions must be required via strings (packageName or require.resolve(packageName)). Read more in minimizerOptions

Boolean

Enable/disable multi-process parallel running.

webpack.config.js

module.exports = {
  optimization: {
    minimize: true,
    minimizer: [
      new CssMinimizerPlugin({
        parallel: true,
      }),
    ],
  },
};

Number

Enable multi-process parallel running and set number of concurrent runs.

webpack.config.js

module.exports = {
  optimization: {
    minimize: true,
    minimizer: [
      new CssMinimizerPlugin({
        parallel: 4,
      }),
    ],
  },
};

minify

Type: Function|Array<Function> Default: CssMinimizerPlugin.cssnanoMinify

Allows overriding default minify function. By default, plugin uses cssnano package. Useful for using and testing unpublished versions or forks.

Possible options:

  • CssMinimizerPlugin.cssnanoMinify
  • CssMinimizerPlugin.cssoMinify
  • CssMinimizerPlugin.cleanCssMinify
  • CssMinimizerPlugin.esbuildMinify
  • CssMinimizerPlugin.lightningCssMinify (previouslyCssMinimizerPlugin.parcelCssMinify, the package was renamed, but we keep it for backward compatibility)
  • async (data, inputMap, minimizerOptions) => {return {code: "a{color: red}", map: "...", warnings: [], errors: []}}

Warning

Always use require inside minify function when parallel option enabled.

Function

webpack.config.js

module.exports = {
  optimization: {
    minimize: true,
    minimizer: [
      new CssMinimizerPlugin({
        minimizerOptions: {
          level: {
            1: {
              roundingPrecision: "all=3,px=5",
            },
          },
        },
        minify: CssMinimizerPlugin.cleanCssMinify,
      }),
    ],
  },
};

Array

If an array of functions is passed to the minify option, the minimizerOptions must also be an array. The function index in the minify array corresponds to the options object with the same index in the minimizerOptions array.

webpack.config.js

module.exports = {
  optimization: {
    minimize: true,
    minimizer: [
      new CssMinimizerPlugin({
        minimizerOptions: [
          {}, // Options for the first function (CssMinimizerPlugin.cssnanoMinify)
          {}, // Options for the second function (CssMinimizerPlugin.cleanCssMinify)
          {}, // Options for the third function
        ],
        minify: [
          CssMinimizerPlugin.cssnanoMinify,
          CssMinimizerPlugin.cleanCssMinify,
          async (data, inputMap, minimizerOptions) => {
            // To do something
            return {
              code: `a{color: red}`,
              map: `{"version": "3", ...}`,
              warnings: [],
              errors: [],
            };
          },
        ],
      }),
    ],
  },
};

minimizerOptions

Type: Object|Array<Object> Default: { preset: 'default' }

Cssnano optimisations options.

Object

module.exports = {
  optimization: {
    minimize: true,
    minimizer: [
      new CssMinimizerPlugin({
        minimizerOptions: {
          preset: [
            "default",
            {
              discardComments: { removeAll: true },
            },
          ],
        },
      }),
    ],
  },
};

Array

The function index in the minify array corresponds to the options object with the same index in the minimizerOptions array. If you use minimizerOptions like object, all minify function accept it.

If a parallelization is enabled, the packages in minimizerOptions must be required via strings (packageName or require.resolve(packageName)). In this case, we shouldn't use require/import.

module.exports = {
  optimization: {
    minimize: true,
    minimizer: [
      new CssMinimizerPlugin({
        minimizerOptions: {
          preset: require.resolve("cssnano-preset-simple"),
        },
      }),
    ],
  },
};
processorOptions (⚠ only cssnano)

Type: Object Default: { from: assetName }

Allows filtering options processoptions for the cssnano. The parser, stringifier and syntax can be either a function or a string indicating the module that will be imported.

Warning

If a function is passed, the parallel option must be disabled..

import sugarss from "sugarss";

module.exports = {
  optimization: {
    minimize: true,
    minimizer: [
      new CssMinimizerPlugin({
        parallel: false,
        minimizerOptions: {
          processorOptions: {
            parser: sugarss,
          },
        },
      }),
    ],
  },
};
module.exports = {
  optimization: {
    minimize: true,
    minimizer: [
      new CssMinimizerPlugin({
        minimizerOptions: {
          processorOptions: {
            parser: "sugarss",
          },
        },
      }),
    ],
  },
};

warningsFilter

Type: Function<(warning, file, source) -> Boolean> Default: () => true

Allow filtering css-minimizer warnings (By default cssnano). Return true to keep the warning, a falsy value (false/null/undefined) otherwise.

Warning

The source argument will contain undefined if you don't use source maps.

webpack.config.js

module.exports = {
  optimization: {
    minimize: true,
    minimizer: [
      new CssMinimizerPlugin({
        warningsFilter: (warning, file, source) => {
          if (/Dropping unreachable code/i.test(warning)) {
            return true;
          }

          if (/file\.css/i.test(file)) {
            return true;
          }

          if (/source\.css/i.test(source)) {
            return true;
          }

          return false;
        },
      }),
    ],
  },
};

Examples

Use sourcemaps

Don't forget to enable sourceMap options for all loaders.

const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");

module.exports = {
  devtool: "source-map",
  module: {
    rules: [
      {
        test: /.s?css$/,
        use: [
          MiniCssExtractPlugin.loader,
          { loader: "css-loader", options: { sourceMap: true } },
          { loader: "sass-loader", options: { sourceMap: true } },
        ],
      },
    ],
  },
  optimization: {
    minimizer: [new CssMinimizerPlugin()],
  },
  plugins: [new MiniCssExtractPlugin()],
};

Remove all comments

Remove all comments (including comments starting with /*!).

module.exports = {
  optimization: {
    minimizer: [
      new CssMinimizerPlugin({
        minimizerOptions: {
          preset: [
            "default",
            {
              discardComments: { removeAll: true },
            },
          ],
        },
      }),
    ],
  },
};

Using custom minifier csso

webpack.config.js

module.exports = {
  // Uncomment if you need source maps
  // devtool: "source-map",
  optimization: {
    minimize: true,
    minimizer: [
      new CssMinimizerPlugin({
        minify: CssMinimizerPlugin.cssoMinify,
        // Uncomment this line for options
        // minimizerOptions: { restructure: false },
      }),
    ],
  },
};

Using custom minifier clean-css

webpack.config.js

module.exports = {
  // Uncomment if you need source maps
  // devtool: "source-map",
  optimization: {
    minimize: true,
    minimizer: [
      new CssMinimizerPlugin({
        minify: CssMinimizerPlugin.cleanCssMinify,
        // Uncomment this line for options
        // minimizerOptions: { compatibility: 'ie11,-properties.merging' },
      }),
    ],
  },
};

Using custom minifier esbuild

webpack.config.js

module.exports = {
  // Uncomment if you need source maps
  // devtool: "source-map",
  optimization: {
    minimize: true,
    minimizer: [
      new CssMinimizerPlugin({
        minify: CssMinimizerPlugin.esbuildMinify,
      }),
    ],
  },
};

Using custom minifier lightningcss, previously @parcel/css

webpack.config.js

module.exports = {
  // Uncomment if you need source maps
  // devtool: "source-map",
  optimization: {
    minimize: true,
    minimizer: [
      new CssMinimizerPlugin({
        minify: CssMinimizerPlugin.lightningCssMinify,
        // Uncomment this line for options
        // minimizerOptions: { targets: { ie: 11 }, drafts: { nesting: true } },
      }),
    ],
  },
};

Using custom minifier swc

webpack.config.js

module.exports = {
  // Uncomment if you need source maps
  // devtool: "source-map",
  optimization: {
    minimize: true,
    minimizer: [
      new CssMinimizerPlugin({
        minify: CssMinimizerPlugin.swcMinify,
        // Uncomment this line for options
        // minimizerOptions: {},
      }),
    ],
  },
};

Contributing

Please take a moment to read our contributing guidelines if you haven't yet done so.

CONTRIBUTING

License

MIT

css-minimizer-webpack-plugin's People

Contributors

0atman avatar alexander-akait avatar alexandruandrei91 avatar amareshsm avatar anshumanv avatar cap-bernardito avatar chenxsan avatar commanderroot avatar dependabot[bot] avatar e1himself avatar efrane avatar ersachin3112 avatar evilebottnawi avatar inokawa avatar krfisc88 avatar lneveu avatar ludofischer avatar mbertheau avatar rdil avatar rschristian avatar snitin315 avatar stu01509 avatar thijstriemstra avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

css-minimizer-webpack-plugin's Issues

Add support for `preamble` option

Hi webpack team 👋

I am currently upgrading a project setup to webpack@5 and want to move from [email protected] to [email protected], but it looks like there is not way to add a simple banner at the top of the emitted CSS asset, so I am unable to put a preamble the same way I was doing this on webpack@4:

optimization: {
  minimizer: [
    new TerserPlugin({
      extractComments: false,
      terserOptions: {
        output: {
          comments: false,
          preamble: preamble, // <-- add preamble to the app.js asset
        },
      },
    }),
  ],
},
plugins: [
  new OptimizeCSSAssetsPlugin({
    cssProcessorPluginOptions: {
      preset: ['default', {
        discardComments: {
          removeAll: true,
        },
      }],
    },
  }),
  new webpack.BannerPlugin({
    raw: true,
    banner: () => {
      return preamble; // <-- add preamble to the app.css asset
    },
  }),
  // ...
]

I guess it's because new CssMinimizerPlugin move into webpack.optimization.minimizer array 🤔
I think it's not a bug, more a feature that is not supported yet.

Feature Proposal

It would be good to have an option to add a banner/preamble at the top of the emitted asset when css-minimizer-webpack-plugin minimization process ends.

Feature Use Case

Same as TerserPlugin with the preamble option: easy to implement and use without any additional plugins.

May be the option should go into CSSNano.. not sure about that.

fix UnhandledPromiseRejectionWarning: DataCloneError: function destructLexErrorInfo()

Bug report

exception during the build

Actual Behavior

build fail because of the error

(node:2528) UnhandledPromiseRejectionWarning: DataCloneError: function destructLexErrorInfo() {
// remove cyclic references added to error info:
          // info....<omitted>... } could not be cloned.
 
at reportError (node_modules\jest-worker\build\workers\threadChild.js:100:32)

at reportClientError (node_modules\jest-worker\build\workers\threadChild.js:84:10)

(Use `node --trace-warnings ...` to show where the warning was created)
(node:2528)
UnhandledPromiseRejectionWarning: Unhandled promise rejection.
This error originated either by throwing inside of an async function without a catch block,
or by rejecting a promise which was not handled with .catch().

To terminate the node process on unhandled promise rejection,
use the CLI flag `--unhandled-rejections=strict`
(see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode).
(rejection id: 1)
(node:2528) [DEP0018] DeprecationWarning:
Unhandled promise rejections are deprecated.
In the future, promise rejections that are not handled will terminate the
Node.js process with a non-zero exit code.

Expected Behavior

build should finish with success

How Do We Reproduce?

follow the README.MD steps for plugin setup

  1. install the npm package
  2. modify webpack config per README.MD
  3. run npm build command per your package.json file

potential security vulnerabilities in your dependencies.

I am getting this message in my package-lock
Could you fix this?

CVE-2021-28092
Moderate severity
The is-svg package 2.1.0 through 4.2.1 for Node.js uses a regular expression that is vulnerable to Regular Expression...

package-lock.json update suggested:
is-svg ~> 4.2.2
Always verify the validity and compatibility of suggestions with your codebase.

Update `css-nano` package

Using css-minimizer-webpack-plugin with version 5.0.0 or above brings problem which described here. In order to fix that behavior you should update css-nano package to 5.0.5 (which actually latest version) and check that current of css-declaration-sorter package is 6.0.3

This is the dependency tree

$ npm ls css-declaration-sorter
[email protected] /Users/user/Desktop/css-minimizer-webpack-plugin
└─┬ [email protected]
  └─┬ [email protected]
    └── [email protected]
  • Operating System: MacOS 11.2.2
  • Node Version: 14.16.0
  • NPM Version: 7.11.0
  • webpack Version: 5.36.2
  • css-minimizer-webpack-plugin Version: 3.0.1

Expected Behavior

described here

Actual Behavior

described here

How Do We Reproduce?

described here

Error: Unexpected '/'. Escaping special characters with \ may help.

"sass": "^1.50.0"
"sass-loader": "^12.6.0"

static/css/4790.810b13a6.css from Css Minimizer plugin
Error: Unexpected '/'. Escaping special characters with \ may help.
at D:\markingCloud\static\css\4790.810b13a6.css:36:1
at Root._error (D:\markingCloud\node_modules\postcss-selector-parser\dist\parser.js:174:16)
at Root.error (D:\markingCloud\node_modules\postcss-selector-parser\dist\selectors\root.js:43:19)
at Parser.error (D:\markingCloud\node_modules\postcss-selector-parser\dist\parser.js:740:21)
at Parser.unexpected (D:\markingCloud\node_modules\postcss-selector-parser\dist\parser.js:759:17)
at Parser.combinator (D:\markingCloud\node_modules\postcss-selector-parser\dist\parser.js:656:12)
at Parser.parse (D:\markingCloud\node_modules\postcss-selector-parser\dist\parser.js:1102:14) at Parser.loop (D:\markingCloud\node_modules\postcss-selector-parser\dist\parser.js:1044:12)
at new Parser (D:\markingCloud\node_modules\postcss-selector-parser\dist\parser.js:164:10)
at Processor._root (D:\markingCloud\node_modules\postcss-selector-parser\dist\processor.js:53:18)
at Processor._runSync (D:\markingCloud\node_modules\postcss-selector-parser\dist\processor.js:100:21)

Misleading webpack configuration

Documentation Is:

  • Missing
  • Needed
  • Confusing
  • Not Sure?

Please Explain in Detail...

I don't think it's a good suggestion to define the webpack configuration as such:

  optimization: {
    minimize: true,
    minimizer: [new CssMinimizerPlugin()],
  },

Problem: the default JS minimizer (Terser) will not be invoked anymore and i don't know how to invoke it without installing it explicitly... It goes against common sense to disable a much wanted behavior especially since this plugin is also about minimization.

Your Proposal for Changes

It seems enough to instantiate an object like this:

    plugins: [
        new CssMinimizerPlugin()
    ]

Like this you don't need to touch the list of minimizers in the optimization entry and you can still have any other plugin in this list.

Example webpack configuration is misleading

Documentation Is: very misleading

  • Missing
  • Needed
  • Confusing
  • Extremely misleading

Please Explain in Detail...

If mini-css-extract-plugin is not required for this plugin to function, it should not be included in the example webpack configuration. Why? I was following this example configuration, and saw that I needed to require two packages: mini-css-extract-plugin and css-minimizer-webpack-plugin. I thought to myself, "ok, this is weird, shouldn't the css-minimizer-webpack-plugin already call mini-css-extract-plugin if its a dependency?" But, after attempting to build unsuccessfully, I found out that mini-css-extract-plugin is not a peerDependency, dependency, or devDependency of css-minimizer-webpack-plugin, meaning that I have to manually install it myself. At this point I was getting quite confused, and installed mini-css-extract-plugin, thinking it would further improve my file size. But lo and behold, the example configuration does not even function! Adding the MiniCssExtractPlugin.loader loader to my CSS section does nothing but make the plugin complain that I did not set it up properly. So I added mini-css-extract-plugin to my plugins list, and what does that do? Nothing but more errors regarding the abscense of document. I then uninstalled mini-css-extract-plugin to find that not using it at all does not affect the performance of css-minimizer-webpack-plugin. If mini-css-extract-plugin serves no purpose regarding this plugin, it should not have been mentioned at all in the example webpack configuration.

Your Proposal for Changes

If mini-css-extract-plugin is not required for this plugin to work, it should not be mentioned in the example configuration. A suggestion to use this plugin may be good, but it should not be in the example configuration.

regression: 4.2.0 causes "Call retries were exceeded" with a fresh, blank Docusaurus project

Bug report

Actual Behavior

Upgrading to 4.2.0 causes the Call retries were exceeded with a fresh docusaurus project when npm run build is ran.

4.1.0 does not exhibit this issue.

Expected Behavior

Css should minimize without issue.

How Do We Reproduce?

npx create-docusaurus@latest my-website classic
cd my-website
npm run build

Observe the minimizer crash:

jamil@mbair:~/tmp/my-website % npm run build

> [email protected] build
> docusaurus build

[INFO] [en] Creating an optimized production build...

✖ Client
  Compiled with some errors in 10.52s

● Server █████████████████████████ building (65%) 1/1 entries 1944/1944 dependencies 625/625 modules 0 active




assets/css/styles.45f640f6.css from Css Minimizer plugin
Error: Call retries were exceeded
assets/css/styles.8ef29f8a.css from Css Minimizer plugin
Error: Call retries were exceeded
[ERROR] Client bundle compiled with errors therefore further build is impossible.

Please paste the results of npx webpack-cli info here, and mention other relevant information

webpack-cli not relevant here

minimizerOptions.processorOptions.map not working

Bug report

processorOptions with { map : { inline : ..., annotation : ... } } does not work.

Actual Behavior

Changing inline true/false and annotation true/false does nothing - the same result.

Expected Behavior

When e.g. inline = false source map should not be created. Also when inline = true and annotation = false annotation in CSS file e.g. /*# sourceMappingURL=file.css.map*/ should be omitted.

How Do We Reproduce?

optimization : {
    minimizer : [
        new CssMinimizerWebpackPlugin({
            minimizerOptions : {
                preset : [ 'default', { discardComments : { removeAll : true } } ],
                processorOptions : { map : { inline : true, annotation : false } },
            },
        }),
    ],
},

When comparing to prev. plugin https://www.npmjs.com/package/optimize-css-assets-webpack-plugin for webpack v4 code below works well...

optimization : {
    minimizer : [
        new OptimizeCssAssetsPlugin({
            cssProcessorPluginOptions : { preset : [ 'default', { discardComments : { removeAll : true } } ] },
            cssProcessorOptions : { map : { inline : false, annotation : true } },
        }),
    ],
},

Im not sure if this is problem just with minimizerOptions.processorOptions.map or glbaly with minimizerOptions.processorOptions

Please paste the results of npx webpack-cli info here, and mention other relevant information

Console is totally clean, no warns no errors just webpack compiled successfully in N ms

Update to cssnano@^5.0.0

I don't see an issue for this, so thought I'd file this to track it.

Feature Proposal

Update to cssnano@^5.0.0 once it is released. cssnano/cssnano#975, cssnano/cssnano#998.

Feature Use Case

Deduplicate postcss dependencies in node_modules when using css-minimizer-webpack-plugin and css-loader.

minimizerOptions fails when not serializable (using import/require)

  • Operating System: macos
  • Node Version: 14.16
  • NPM Version: 6
  • webpack Version: 5.28.0
  • css-minimizer-webpack-plugin Version: 2.0.0

Expected Behavior

Using cssnano preset with a require call instead of a string preset + options object:

      new CssMinimizerPlugin({
        minimizerOptions: [
          // CssNano options
          {
            preset: require('cssnano-preset-advanced'), 
          },
        ],
        minify: [
          CssMinimizerPlugin.cssnanoMinify,
        ],
      })

Actual Behavior

ReferenceError: defaultOpts is not defined

image

Also tried with preset: require('cssnano-preset-advanced')(opts) (looks like the correct way to me) and got another similar error:

image

ReferenceError: _commentRemover is not defined

Code

cf above

How Do We Reproduce?

cf above


For context, Docusaurus is migrating to Webpack 5 (@alexander-akait helped review a bit our PR facebook/docusaurus#4089)

We have a custom CSSNano preset with some custom config + an additional postcss plugin: https://github.com/facebook/docusaurus/tree/master/packages/docusaurus-cssnano-preset

It's not 100% clear to me how I am supposed to provide our custom Cssnano preset to the CssMinimizer, as it seems there's some evaluation of options that prevent imports/requires in our preset. Do you have an example to share?

I believe that it is a similar issue that @RDIL already reported here: #58

Jest worker doesn't let me see actual error, shows UnhandledPromiseRejectionWarning instead

  • Operating System: macOS Big Sur
  • Node Version: v14.15.4
  • NPM Version: 6.14.10 (yarn 1.22.10)
  • webpack Version: 5.38.1 (webpacker 6.0.0-beta.7)
  • css-minimizer-webpack-plugin Version: 3.0.2

Expected Behavior

When an error happens while running CssMinimizerPlugin, I should be able to see what's wrong so I can fix it.

Actual Behavior

Jest Worker swallows the error and doesn't show me a meaningful backtrace, I have no idea how to fix it.
This is all I see in the compilation output...

92% sealing asset processing CssMinimizerPlugin
UnhandledPromiseRejectionWarning: DataCloneError: function destructLexErrorInfo() {
          // remove cyclic references added to error info:
          // info....<omitted>... } could not be cloned.
    at reportError (/Users/mattiagiuffrida/Development/sensortower/overseer/node_modules/jest-worker/build/workers/threadChild.js:100:32)
    at reportClientError (/Users/mattiagiuffrida/Development/sensortower/overseer/node_modules/jest-worker/build/workers/threadChild.js:84:10)

Code

const { webpackConfig, merge } = require('@rails/webpacker');

process.env.NODE_ENV = process.env.NODE_ENV || 'production';

const prodConfig = {
  mode: 'production',
  devtool: false,
  optimization: {
    chunkIds: 'size',
    splitChunks: {
      cacheGroups: {
        default: false,
      },
    },
    runtimeChunk: false,
  }
};

module.exports = merge(webpackConfig, prodConfig);

How Do We Reproduce?

Hard to say since I don't know what's wrong 😄 !

Set appropriate defaults for clean-css and csso

Feature Proposal

Allow clean-css and csso to be set as configuration options, and appropriate defaults applied. It's quite convenient to use default of cssnano, where you just need to set the cssnano options. But if you want to use any of the alternatives, you need a lot of configuration to override the minify function as shown in readme. It could just be given as a config value or which minifier you want to use, and appropriate defaults set.

minimizerOptions config doesn't work

Actual Behavior

minimizerOptions config doesn't work.

Expected Behavior

still transform color

source code:

body {
    color: transparent;
}

config:

optimization: {
        minimize: true,
        minimizer: [
            new TerserPlugin(),
            new CssMinimizerPlugin({
                minimizerOptions: {
                    preset: [
                        'default',
                        {
                            colormin: {
                                transparent: false,
                            },
                        },
                    ],
                },
            }),
        ],
    },

colormin options: https://github.com/cssnano/cssnano/blob/master/packages/postcss-colormin/src/index.js#L91

minify code:

body{color:#0000}

How Do We Reproduce?

  1. git clone [email protected]:tjx666/webpack-css-minify-issue.git
  2. pnpm install
  3. pnpm run build
  4. open dist/main.css
  5. you can see the color tansparen is transformed to hex

Please paste the results of npx webpack-cli info here, and mention other relevant information

System:
    OS: macOS 12.6
    CPU: (8) x64 Intel(R) Core(TM) i5-8257U CPU @ 1.40GHz
    Memory: 405.14 MB / 16.00 GB
  Binaries:
    Node: 16.17.0 - ~/.nvm/versions/node/v16.17.0/bin/node
    Yarn: 1.22.19 - ~/.nvm/versions/node/v16.17.0/bin/yarn
    npm: 8.19.2 - ~/.nvm/versions/node/v16.17.0/bin/npm
  Browsers:
    Chrome: 105.0.5195.125
    Firefox Developer Edition: 104.0
    Safari: 16.0
  Packages:
    css-loader: 6.7.1 => 6.7.1 
    css-minimizer-webpack-plugin: 4.1.0 => 4.1.0 
    terser-webpack-plugin: 5.3.6 => 5.3.6 
    webpack: 5.74.0 => 5.74.0 
    webpack-cli: 4.10.0 => 4.10.0 

Allow providing custom PostCSS options

  • Operating System: Ubuntu 18.04
  • Node Version: 12.14.0
  • NPM Version: 6.13.4
  • webpack Version: 4
  • css-minimizer-webpack-plugin Version: 1.2.0

Feature Proposal

Allow specifying custom options for PostCSS process, as https://github.com/NMFR/optimize-css-assets-webpack-plugin does (cssProcessorOptions option).
The options object is defined here and cannot be extended.

Feature Use Case

Into Quasar Framework we use https://github.com/postcss/postcss-safe-parser via the parser PostCSS option.

A possible patch would be to copy/paste the internal minify function into an external provided minify one, with the options we prefer

Output not minified and minified files

Hello 👋

I don't get how to output not minified and minified CSS files using mini-css-extract-plugin and css-minizer-webpack-plugin at the same time.

When it runs, I only get the minified CSS as theme.css.

Here is my webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');

module.exports = (env, argv) => ({
	mode: argv.mode === 'development' ? 'development' : 'production',
	entry: './src/index.js',
	output: {
		filename: 'theme.js',
		path: path.resolve(__dirname, './dist'),,
	},
	module: {
		rules: [
			{
				test: /\.woff(2)?(\?[a-z0-9=&.]+)?$/,
				loader: 'url-loader',
				options: {
					limit: 10000,
					mimetype: 'application/font-woff',
					name: './fonts/[name].[ext]',
				},
			},
			{
				test: /theme\.scss$/,
				use: [
					{
						loader: argv.mode === 'development' ? 'style-loader' : MiniCssExtractPlugin.loader,
					},
					{
						loader: 'css-loader',
						options: {
							importLoaders: 1,
							minimize: true,
							sourceMap: true,
						},
					},
					{
						loader: 'sass-loader',
						options: {
							sourceMap: true,
						},
					},
				],
			},
		],
	},
	devtool: 'source-map',
	optimization: {
		minimize: true,
		minimizer: [
			`...`,
			new CssMinimizerPlugin(),
		],
	},
	plugins: [
		argv.mode !== 'development' &&
			new MiniCssExtractPlugin({
				filename: 'theme.css',
			}),
	].filter(Boolean),
});

Here my dependencies

{
  "devDependencies": {
    "css-loader": "^1.0.1",
    "css-minimizer-webpack-plugin": "^1.3.0",
    "file-loader": "^6.2.0",
    "mini-css-extract-plugin": "^1.3.9",
    "node-sass": "^5.0.0",
    "postcss-loader": "^5.2.0",
    "postcss-preset-env": "^6.7.0",
    "sass-loader": "^11.0.1",
    "style-loader": "^2.0.0",
    "url-loader": "^4.1.1",
    "webpack": "^5.25.1",
    "webpack-cli": "^4.5.0",
    "webpack-dev-server": "^3.11.2"
  },
}

What could be wrong, here?

README confusing about how to enable for development as well

Documentation Is:

  • Missing
  • Needed
  • Confusing
  • Not Sure?

Please Explain in Detail...

In README.md it says:

webpack.config.js

const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');

module.exports = {
  module: {
    loaders: [
      {
        test: /.s?css$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
      },
    ],
  },
  optimization: {
    minimize: true,
    minimizer: [
      // For webpack@5 you can use the `...` syntax to extend existing minimizers (i.e. `terser-webpack-plugin`), uncomment the next line
      // `...`,
      new CssMinimizerPlugin(),
    ],
  },
};

This will enable CSS optimization only in production mode.

Ok, so this example is for CSS optimization only in production mode.

If you want to run it also in development set the optimization.minimize option to true.

Ok, to run it in development mode as well, set optimization.minimize option to true.

Wait: It's already true in the example?

Your Proposal for Changes

I'm confused, so I don't know :) Either the example should be modified such that it actually enables CSS optimization only in production mode, or the explanation about how to enable CSS optimization also in development mode needs to be changed.

Source map content from previous processing step is ignored

Bug report

When css-minimizer-webpack-plugin is used, source map content from previous step is ignore and completely replaced and not merge with the one that came from minification.

Actual Behavior

In debug mode, you can inspect the DOM elements in the browsers devtool and see the original source of applied rulesets.
In release mode, due css-minimizer-webpack-plugin apply minification, you only see the source before minification, not the original one.

Expected Behavior

When you inspect DOM elements in the browsers devtool you can see the original source of applied rulesets in any mode (release, debug, etc.)

How Do We Reproduce?

Compile styles with a preprocessor (sass, less, stylus, etc.) with sourcemap without css-minimizer-webpack-plugin (or disabled with debug mode), inspect the extracted source map with devtool or source-map-visualization.
Do it again but with css-minimizer-webpack-plugin, then it inspect again.

Reproducible test: webpack-source-map-merge-test

Please paste the results of npx webpack-cli info here, and mention other relevant information

  System:
    OS: Windows 8.1 6.3.9600
    CPU: (4) x64 Intel(R) Core(TM) i5-6500 CPU @ 3.20GHz
    Memory: 6.94 GB / 31.88 GB
  Binaries:
    Node: 14.17.4 - C:\Program Files\nodejs\node.EXE
    npm: 6.14.14 - C:\Program Files\nodejs\npm.CMD
  Browsers:
    Chrome: 95.0.4638.69
    Internet Explorer: 11.0.9600.19036
  Packages:
    webpack: ^5.61.0 => 5.62.2
    webpack-cli: ^4.9.1 => 4.9.1

Possible solutions

Each minimizer has it's own option/solution:

It's also possible to not provide previous source map to the minimizer but instead manually merge source maps:

const { SourceMapGenerator } = require('source-map/lib/source-map-generator.js');
const { SourceMapConsumer } = require('source-map/lib/source-map-consumer.js');

const mergedSourceMap = await SourceMapConsumer.with(resultSourceMap, null, async (resultConsumer) =>
  SourceMapConsumer.with(inputSourceMap, null, inputConsumer => {
    const generator = SourceMapGenerator.fromSourceMap(resultConsumer);
    generator.applySourceMap(inputConsumer, filename);
    return generator.toJSON();
  }));

Example of implementation with cssnano:

diff --git a/src/utils.jst b/src/utils.js
index 08829e0..19b90f3 100644
--- a/src/utils.js
+++ b/src/utils.js
@@ -116,7 +116,10 @@ async function cssnanoMinify(
   }

   if (inputSourceMap) {
-    postcssOptions.map = { annotation: false };
+    postcssOptions.map = {
+      annotation: false,
+      prev: inputSourceMap,
+    };
   }

   // eslint-disable-next-line global-require

Update README.md

Documentation Is:

  • Missing
  • Needed
  • Confusing
  • Not Sure?

Please Explain in Detail...

The message in the readme.md on line 50 regarding `...` syntax is confusing.

Your Proposal for Changes

I'd like to propose to change README.md

optimization: {
    minimize: true,
    minimizer: [
      // For webpack@5 you can use the `...` syntax to extend existing minimizers (i.e. `terser-webpack-plugin`), uncomment the next line
      // ...new CssMinimizerPlugin(),
      new CssMinimizerPlugin(),
    ],
  },

PostCSS types not included; TypeError

Bug report

When using css-minimizer-webpack-plugin with npm 7.7.6 and Typescript, the cssnano/node_modules/postcss is not being installed. As a result, builds fail on this type error.

Actual Behavior


node_modules/css-minimizer-webpack-plugin/types/utils.d.ts:9:30 - error TS2307: Cannot find module 'cssnano/node_modules/postcss' or its corresponding type declarations.

9 export type CssNano = import("cssnano/node_modules/postcss").Plugin<
                               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


Found 1 error.

Expected Behavior

I know I'm not supposed to say "it should work", but, uh. It looks like you're pulling a type from somewhere that is unreliable. From what I can tell, it's possibly be the result of @types/cssnano being a direct dependency in your package (and getting it's deps installed), but being a transitive dependency when it's being used. Not sure. What I do know for certain is that in my project that's using css-minimizer-webpack-plugin, the @types/cssnano folder looks like this:

Screen Shot 2021-12-20 at 2 34 06 PM

When you pull down css-minimizer-webpack-plugin directly, it looks like this:

Screen Shot 2021-12-20 at 2 37 36 PM

How Do We Reproduce?

Using css-minimizer-webpack-plugin in a Typescript project should trigger this.

Please paste the results of npx webpack-cli info here, and mention other relevant information

forge [get-css-smaller-nh] $ npx webpack-cli info

  System:
    OS: macOS 11.6.1
    CPU: (8) x64 Intel(R) Core(TM) i7-1068NG7 CPU @ 2.30GHz
    Memory: 1.35 GB / 32.00 GB
  Binaries:
    Node: 15.14.0 - ~/.nvm/versions/node/v15.14.0/bin/node
    Yarn: 1.22.10 - /usr/local/bin/yarn
    npm: 7.7.6 - ~/.nvm/versions/node/v15.14.0/bin/npm
  Browsers:
    Chrome: 96.0.4664.110
    Firefox: 91.4.0
    Safari: 15.2
  Packages:
    css-loader: ^6.2.0 => 6.5.1
    css-minimizer-webpack-plugin: ^3.1.4 => 3.3.0
    csv-loader: ^3.0.3 => 3.0.3
    filemanager-webpack-plugin: ^6.1.4 => 6.1.7
    html-webpack-plugin: ^5.3.2 => 5.5.0
    style-loader: ^3.2.1 => 3.3.1
    ts-loader: ^9.2.3 => 9.2.6
    webpack: ^5.45.1 => 5.65.0
    webpack-bundle-analyzer: ^4.5.0 => 4.5.0
    webpack-cli: ^4.7.2 => 4.9.1
    webpack-dev-server: ^3.11.2 => 3.11.3
    xml-loader: ^1.2.1 => 1.2.1

I suspect that if you change the type to point at postcss instead of cssnano/node_modules/postcss that this error will go away, but you may need to add @types/postcss to your dependencies.

Feature: Add Lightning CSS (renamed @parcel/css)

Feature Proposal

Devon released Lightning CSS: https://twitter.com/devongovett/status/1567898042787049473
It's the same as @parcel/css but now with a different name.

https://lightningcss.dev/

So it'll be a matter of changing dependencies and names to support this new, old package.

I'm happy to do the work if y'all can give me directions on how you typically handle such renames. I'd imagine just removing the parcelCssMinify option is not ideal as it would be a breaking change. So maybe gracefully handle that option for now and fallback to the new lightningCssMinify option then? So the options passed to parcelCssMinify would be just passed through to lightningCssMinify.

Thanks for your work and the plugins!

Strange issue relating to option escaping & undefined input

)(exports, require, module, __filename, __dirname);

⬆️ That code causes a strange error within a project I am currently working on:

 Client
  Compiled with some errors in 1.28m

 Server █████████████████████████ building (64%) 1/1 entries 2744/2744 dependencies 932/932 modules 0 active 

{
  errors: [
    {
      message: 'assets/css/styles.31e70bd7.css from Css Minimizer\n' +
        'ReferenceError: initializer is not defined\n' +
        '    at creator (eval at transform (/workspace/docusaurus/node_modules/css-minimizer-webpack-plugin/dist/minify.js:62:13), <anonymous>:5:23)\n' +
        '    at initializePlugin (/workspace/docusaurus/node_modules/cssnano/dist/index.js:31:36)\n' +
        '    at processTicksAndRejections (internal/process/task_queues.js:93:5)'
    }
  ],
}
Client bundle compiled with errors therefore further build is impossible.

Interestingly enough, applying the following patch to this plugin fixes this error, but causes others.

diff --git a/node_modules/css-minimizer-webpack-plugin/dist/minify.js b/node_modules/css-minimizer-webpack-plugin/dist/minify.js
index 69ce92f..c189b98 100644
--- a/node_modules/css-minimizer-webpack-plugin/dist/minify.js
+++ b/node_modules/css-minimizer-webpack-plugin/dist/minify.js
@@ -59,7 +59,7 @@ async function transform(options) {
   // 'use strict' => this === undefined (Clean Scope)
   // Safer for possible security issues, albeit not critical at all here
   // eslint-disable-next-line no-new-func, no-param-reassign
-  options = new Function('exports', 'require', 'module', '__filename', '__dirname', `'use strict'\nreturn ${options}`)(exports, require, module, __filename, __dirname);
+  // options = new Function('exports', 'require', 'module', '__filename', '__dirname', `'use strict'\nreturn ${options}`)(exports, require, module, __filename, __dirname);
   const result = await minify(options);
 
   if (result.error) {

New errors:

{
  errors: [
    {
      message: 'assets/css/styles.d52d4cdd.css from Css Minimizer\n' +
        'Error: PostCSS received undefined instead of CSS string\n' +
        '    at new Input (/workspace/docusaurus/node_modules/postcss/lib/input.js:38:13)\n' +
        '    at parse (/workspace/docusaurus/node_modules/postcss/lib/parse.js:13:15)\n' +
        '    at new LazyResult (/workspace/docusaurus/node_modules/postcss/lib/lazy-result.js:64:16)\n' +
        '    at Processor.<anonymous> (/workspace/docusaurus/node_modules/postcss/lib/processor.js:142:12)\n' +
        '    at Processor.process (/workspace/docusaurus/node_modules/postcss/lib/processor.js:121:23)\n' +
        '    at Function.creator.process (/workspace/docusaurus/node_modules/postcss/lib/postcss.js:148:43)\n' +
        '    at minify (/workspace/docusaurus/node_modules/css-minimizer-webpack-plugin/dist/minify.js:50:32)\n' +
        '    at Object.transform (/workspace/docusaurus/node_modules/css-minimizer-webpack-plugin/dist/minify.js:63:24)\n' +
        '    at execFunction (/workspace/docusaurus/node_modules/css-minimizer-webpack-plugin/node_modules/jest-worker/build/workers/processChild.js:145:17)\n' +
        '    at execHelper (/workspace/docusaurus/node_modules/css-minimizer-webpack-plugin/node_modules/jest-worker/build/workers/processChild.js:124:5)'
    },
    {
      message: 'assets/css/styles.d52d4cdd.css from Css Minimizer\n' +
        'Error: PostCSS received undefined instead of CSS string\n' +
        '    at new Input (/workspace/docusaurus/node_modules/postcss/lib/input.js:38:13)\n' +
        '    at parse (/workspace/docusaurus/node_modules/postcss/lib/parse.js:13:15)\n' +
        '    at new LazyResult (/workspace/docusaurus/node_modules/postcss/lib/lazy-result.js:64:16)\n' +
        '    at Processor.<anonymous> (/workspace/docusaurus/node_modules/postcss/lib/processor.js:142:12)\n' +
        '    at Processor.process (/workspace/docusaurus/node_modules/postcss/lib/processor.js:121:23)\n' +
        '    at Function.creator.process (/workspace/docusaurus/node_modules/postcss/lib/postcss.js:148:43)\n' +
        '    at minify (/workspace/docusaurus/node_modules/css-minimizer-webpack-plugin/dist/minify.js:50:32)\n' +
        '    at Object.transform (/workspace/docusaurus/node_modules/css-minimizer-webpack-plugin/dist/minify.js:63:24)\n' +
        '    at execFunction (/workspace/docusaurus/node_modules/css-minimizer-webpack-plugin/node_modules/jest-worker/build/workers/processChild.js:145:17)\n' +
        '    at execHelper (/workspace/docusaurus/node_modules/css-minimizer-webpack-plugin/node_modules/jest-worker/build/workers/processChild.js:124:5)'
    },
    {
      message: 'assets/css/styles.06531b13.css from Css Minimizer\n' +
        'Error: PostCSS received undefined instead of CSS string\n' +
        '    at new Input (/workspace/docusaurus/node_modules/postcss/lib/input.js:38:13)\n' +
        '    at parse (/workspace/docusaurus/node_modules/postcss/lib/parse.js:13:15)\n' +
        '    at new LazyResult (/workspace/docusaurus/node_modules/postcss/lib/lazy-result.js:64:16)\n' +
        '    at Processor.<anonymous> (/workspace/docusaurus/node_modules/postcss/lib/processor.js:142:12)\n' +
        '    at Processor.process (/workspace/docusaurus/node_modules/postcss/lib/processor.js:121:23)\n' +
        '    at Function.creator.process (/workspace/docusaurus/node_modules/postcss/lib/postcss.js:148:43)\n' +
        '    at minify (/workspace/docusaurus/node_modules/css-minimizer-webpack-plugin/dist/minify.js:50:32)\n' +
        '    at Object.transform (/workspace/docusaurus/node_modules/css-minimizer-webpack-plugin/dist/minify.js:63:24)\n' +
        '    at execFunction (/workspace/docusaurus/node_modules/css-minimizer-webpack-plugin/node_modules/jest-worker/build/workers/processChild.js:145:17)\n' +
        '    at execHelper (/workspace/docusaurus/node_modules/css-minimizer-webpack-plugin/node_modules/jest-worker/build/workers/processChild.js:124:5)'
    },
    {
      message: 'assets/css/styles.06531b13.css from Css Minimizer\n' +
        'Error: PostCSS received undefined instead of CSS string\n' +
        '    at new Input (/workspace/docusaurus/node_modules/postcss/lib/input.js:38:13)\n' +
        '    at parse (/workspace/docusaurus/node_modules/postcss/lib/parse.js:13:15)\n' +
        '    at new LazyResult (/workspace/docusaurus/node_modules/postcss/lib/lazy-result.js:64:16)\n' +
        '    at Processor.<anonymous> (/workspace/docusaurus/node_modules/postcss/lib/processor.js:142:12)\n' +
        '    at Processor.process (/workspace/docusaurus/node_modules/postcss/lib/processor.js:121:23)\n' +
        '    at Function.creator.process (/workspace/docusaurus/node_modules/postcss/lib/postcss.js:148:43)\n' +
        '    at minify (/workspace/docusaurus/node_modules/css-minimizer-webpack-plugin/dist/minify.js:50:32)\n' +
        '    at Object.transform (/workspace/docusaurus/node_modules/css-minimizer-webpack-plugin/dist/minify.js:63:24)\n' +
        '    at execFunction (/workspace/docusaurus/node_modules/css-minimizer-webpack-plugin/node_modules/jest-worker/build/workers/processChild.js:145:17)\n' +
        '    at execHelper (/workspace/docusaurus/node_modules/css-minimizer-webpack-plugin/node_modules/jest-worker/build/workers/processChild.js:124:5)'
    }
  ]
}
Client bundle compiled with errors therefore further build is impossible.

Thanks in advance for any help!!

Relevant config:

new CssMinimizerPlugin({
      minimizerOptions: {
        preset: CssNanoPreset,
      }
    }),
    new CssMinimizerPlugin({
      minimizerOptions: {
        cssProcessor: CleanCss,
      }
    }),

CssNanoPreset is @docusaurus/cssnano-preset, CleanCSS is clean-css.

Not working with 2 minimizers

  • Operating System: n/a
  • Node Version: 12 and 14 both
  • NPM Version: latest 6.x
  • webpack Version: 5.24.2
  • css-minimizer-webpack-plugin Version: 1.2.0

Expected Behavior

In facebook/docusaurus#4089, we use 2 minimizers. It appears that one of them isn't getting applied because the css has unexpectedly raised in size by 4kb. Any support or thoughts would be appreciated.

Actual Behavior

It doesn't appear to be performing the same optimization

Code

See the code below this discussion https://github.com/facebook/docusaurus/pull/4089/files#r588305123

How Do We Reproduce?

facebook/docusaurus#4089
It worked with css-optimizer-webpack-plugin, now it doesn't

Error: [object Object] is not a PostCSS plugin on the centos7.2

Bug report

 message: 'static/css/styles.febb911f.css from Css Minimizer\n' +
       'Error: [object Object] is not a PostCSS plugin\n' +
       '    at Processor.normalize (workspace/node_modules/postcss/lib/processor.js:168:15)\n' +
       '    at new Processor (workspace/node_modules/postcss/lib/processor.js:52:25)\n' +
       '    at postcss (workspace/node_modules/postcss/lib/postcss.js:55:10)\n' +
       '    at cssnanoPlugin (workspace/node_modules/cssnano/dist/index.js:145:31)\n' +
       '    at cssnanoMinify (eval at transform (workspace/node_modules/css-minimizer-webpack-plugin/dist/minify.js:34:28), :49:33)\n' +
       '    at minify (workspace/node_modules/css-minimizer-webpack-plugin/dist/minify.js:15:32)\n' +
       '    at Object.transform (workspace/node_modules/css-minimizer-webpack-plugin/dist/minify.js:35:24)\n' +
       '    at execFunction (workspace/node_modules/css-minimizer-webpack-plugin/node_modules/jest-worker/build/workers/threadChild.js:158:17)\n' +
       '    at execHelper (workspace/node_modules/css-minimizer-webpack-plugin/node_modules/jest-worker/build/workers/threadChild.js:137:5)\n' +
       '    at execMethod (workspace/node_modules/css-minimizer-webpack-plugin/node_modules/jest-worker/build/workers/threadChild.js:141:5)'
   }

Actual Behavior

There is no error when running build on centos7.2.
There is no problem running build on a local MAC

Both environment node versions are V12 +

Run failed

Expected Behavior

Compression and no errors

How Do We Reproduce?

this is webpack.config.js

const { merge } = require('webpack-merge');
const common = require('./webpack.common');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');

module.exports = merge(common({isDev: false}), {
  mode: 'production',
  bail: true,
  optimization: {
    usedExports:true,
    minimizer: [
      `...`,
      new CssMinimizerPlugin()
    ]
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: 'static/css/[name].[contenthash:8].css',
      chunkFilename: 'static/css/[name].[contenthash:8].chunk.css',
      ignoreOrder: true
    })
  ].filter(Boolean)
});

Please paste the results of npx webpack-cli info here, and mention other relevant information

The execution mode is as follows:

const prodWebpackConfig = require('../config/webpack.prod');
const compiler = webpack(prodWebpackConfig);
compiler.run((err, stats) => {})

I do not understand how it works with TerserPlugin

Documentation Is:

  • Missing
  • Needed
  • Confusing
  • Not Sure?

I do not understand how it works with TerserPlugin and I'm not the first one #46

minimize: isEnvProduction,
minimizer: [
  // This is only used in production mode
  new TerserPlugin({
    parallel: true,
    terserOptions: {
      parse: {
        ecma: 8
      },
      // ...
    }
  }),
  new CssMinimizerPlugin({
    minimizerOptions: {
      processorOptions: {
        parser: safePostCssParser,
        map: false
      },
      preset: ['default', {
        discardComments: { removeAll: true },
        minifyFontValues: { removeQuotes: false }
      }]
    }
  })
  /*
    Creating an optimized production build...
    Error parsing bundle asset "/home/user/project/build/js/app.js": no such file
    Error parsing bundle asset "/home/user/project/build/js/loading.js": no such file

    No bundles were parsed. Analyzer will show only original module sizes from stats file.

    Webpack Bundle Analyzer saved report to /home/user/project/sizeReport.html
    Failed to compile.

    css/loading.css from Css Minimizer
    ReferenceError: Input is not defined
  */

  // ...new CssMinimizerPlugin(...) // TypeError: CssMinimizerPlugin is not a function or its return value is not iterable
],

I tried also this

minimize: isEnvProduction,
minimizer: [
  new TerserPlugin({
    // ...
    ...new CssMinimizerPlugin(...)
    /*
      ValidationError: Invalid options object. Terser Plugin has been initialized using an options object that does not match the API schema.
       - options has an unknown property 'options'.
     */
    
    ...new CssMinimizerPlugin(...).options
    /*
      ValidationError: Invalid options object. Terser Plugin has been initialized using an options object that does not match the API schema.
       - options has an unknown property 'minimizerOptions'.
     */
  })
]

preset lite + options doesn't pass options

  • Operating System: Big Sur
  • Node Version: 15
  • webpack Version: 5.37
  • css-minimizer-webpack-plugin Version: 2.0
             new CssMinimizerPlugin({
                // this doesnt discard duplicates....
                minimizerOptions: {
                  preset: [
                    'lite',
                    {
                      discardDuplicates: true,
                    },
                  ],
                },
              }),

Using this config I'm unable to get cssnano to discard duplicates, tried a few different variants. Perhaps this isn't possible? But readme suggests it should work work.

TypeScript errors with array of minifiers after upgrading

Bug report

Upgrading from 3.1.4 to 3.3.1 is causing TypeScript errors with the "array syntax":

https://github.com/webpack-contrib/css-minimizer-webpack-plugin#array

Not 100% sure why this happens but it looks like now typedefs are included in this package while we used DefinitivelyTyped before?

Actual Behavior

The README array example does not work with TypeScript:

https://github.com/webpack-contrib/css-minimizer-webpack-plugin#array

const test = new CssMinimizerPlugin({
  minimizerOptions: [
    {}, // Options for the first function (CssMinimizerPlugin.cssnanoMinify)
    {}, // Options for the second function (CssMinimizerPlugin.cleanCssMinify)
    {}, // Options for the third function
  ],
  minify: [
    CssMinimizerPlugin.cssnanoMinify,
    CssMinimizerPlugin.cleanCssMinify,
    async (data, inputMap, minimizerOptions) => {
      // To do something
      return {
        code: `a{color: red}`,
        map: `{"version": "3", ...}`,
        warnings: [],
        errors: [],
      };
    },
  ],
});

image

I tried to pass an explicit generic like CustomOptions but not sure if it's what I should do.

Expected Behavior

How Do We Reproduce?

Readme example with TS

Please paste the results of npx webpack-cli info here, and mention other relevant information

Not relevant.

Env is latest version + TS 4.5

SourceMap option does not work on GitLab CI

  • Operating System: GitLab CI - Docker/Ubuntu
  • Node Version: 14.15.3
  • NPM Version: 6.14.9
  • webpack Version: 5.11.1
  • css-minimizer-webpack-plugin Version: 1.1.5

Expected Behavior

Should produce a sourcemap on GitLab CI in the same way as on my local machine.

Actual Behavior

Fails with the following error message:

(node:47) UnhandledPromiseRejectionWarning: Error: "version" is a required argument.
    at Object.getArg (/builds/ofhouse/stackoverflow-65355772/node_modules/source-map/lib/util.js:24:11)
    at new BasicSourceMapConsumer (/builds/ofhouse/stackoverflow-65355772/node_modules/source-map/lib/source-map-consumer.js:294:22)
    at new SourceMapConsumer (/builds/ofhouse/stackoverflow-65355772/node_modules/source-map/lib/source-map-consumer.js:22:7)
    at SourceMapSource.node (/builds/ofhouse/stackoverflow-65355772/node_modules/webpack-sources/lib/SourceMapSource.js:193:4)
    at exports.getSourceAndMap (/builds/ofhouse/stackoverflow-65355772/node_modules/webpack-sources/lib/helpers.js:20:27)
    at SourceMapSource.sourceAndMap (/builds/ofhouse/stackoverflow-65355772/node_modules/webpack-sources/lib/SourceMapSource.js:184:10)
    at getTaskForFile (/builds/ofhouse/stackoverflow-65355772/node_modules/webpack/lib/SourceMapDevToolPlugin.js:78:30)
    at /builds/ofhouse/stackoverflow-65355772/node_modules/webpack/lib/SourceMapDevToolPlugin.js:266:22
    at /builds/ofhouse/stackoverflow-65355772/node_modules/webpack/lib/Cache.js:93:5
    at Hook.eval [as callAsync] (eval at create (/builds/ofhouse/stackoverflow-65355772/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:6:1)

Code

Reproduction repository: https://gitlab.com/ofhouse/stackoverflow-65355772

How Do We Reproduce?

  1. Checkout the repository locally and run npm run build (success)
  2. Upload it to GitLab.com and let GitLab CI run (fails)
    Example output from the current HEAD of the repository: https://gitlab.com/ofhouse/stackoverflow-65355772/-/jobs/945541367

I've tried out many different setups but I always fail to reproduce the issue locally.
Even running inside the same docker image with

docker run --rm -v $(pwd):/tmp node:14-alpine sh -c "cd /tmp && npm ci && npm run build"

does not let me reproduce the issue.

I have no idea how I could abstract this issue further, so my hope is that somebody here has an idea what's happening 🙏.

Edit:
What it makes it even stranger is that it also runs successfully on GitHub actions: https://github.com/ofhouse/stackoverflow-65355772/runs/1652026529

Possible regression in v3.1.0 with "Minimizer function doesn't return result"

Bug report

Actual Behavior

It looks like the recent release of v3.1.0 introduced a possible regression.
I'm not using css-minimizer-webpack-plugin directly, as I am a user of Vue CLI and the CLI handles the webpack config.

Expected Behavior

The repro with the CLI is here. I know this is not a minimal reproduction, and I'm sorry. Feel free to close the issue if that's not helpful, but downgrading css-minimizer-webpack-plugin to v3.0.2 instead of v3.1.0 fixes the issue, so I suspect there is a regression somewhere as nothing changed in the Vue CLI configuration.

The CLI uses it internally like this:
https://github.com/vuejs/vue-cli/blob/57926ab3c1fcfde88261df5f2885a2a70637034a/packages/%40vue/cli-service/lib/config/css.js#L220-L231

How Do We Reproduce?

https://github.com/cexbrayat/css-mini

This is a bare project created with the CLI. This project fails with the error:

⠋  Building for production...

 ERROR  Failed to compile with 1 error                                                                                               10:18:52

 error  in css/app.8a97e00d.css

css/app.8a97e00d.css from Css Minimizer Plugin
Error: Minimizer function doesn't return result
    at minify (/Users/ced-pro/Code/test/vue-cli-tests/css-mini/node_modules/css-minimizer-webpack-plugin/dist/minify.js:29:13)
    at async Object.transform (/Users/ced-pro/Code/test/vue-cli-tests/css-mini/node_modules/css-minimizer-webpack-plugin/dist/minify.js:62:18)

 ERROR  Error: Build failed with errors.
Error: Build failed with errors.
    at /Users/ced-pro/Code/test/vue-cli-tests/css-mini/node_modules/@vue/cli-service/lib/commands/build/index.js:207:23
    at /Users/ced-pro/Code/test/vue-cli-tests/css-mini/node_modules/webpack/lib/webpack.js:141:8
    at /Users/ced-pro/Code/test/vue-cli-tests/css-mini/node_modules/webpack/lib/HookWebpackError.js:68:3
    at Hook.eval [as callAsync] (eval at create (/Users/ced-pro/Code/test/vue-cli-tests/css-mini/node_modules/webpack/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:6:1)
    at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (/Users/ced-pro/Code/test/vue-cli-tests/css-mini/node_modules/webpack/node_modules/tapable/lib/Hook.js:18:14)
    at Cache.shutdown (/Users/ced-pro/Code/test/vue-cli-tests/css-mini/node_modules/webpack/lib/Cache.js:150:23)
    at /Users/ced-pro/Code/test/vue-cli-tests/css-mini/node_modules/webpack/lib/Compiler.js:1156:15
    at Hook.eval [as callAsync] (eval at create (/Users/ced-pro/Code/test/vue-cli-tests/css-mini/node_modules/webpack/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:6:1)
    at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (/Users/ced-pro/Code/test/vue-cli-tests/css-mini/node_modules/webpack/node_modules/tapable/lib/Hook.js:18:14)
    at Compiler.close (/Users/ced-pro/Code/test/vue-cli-tests/css-mini/node_modules/webpack/lib/Compiler.js:1149:23)
error Command failed with exit code 1.

I opened an issue on the CLI side, but thought that this was maybe a upstream issue, as this is working fine if we force the CLI to use v3.0.2 via a resolution.

See vuejs/vue-cli#6723 for more details

Please paste the results of npx webpack-cli info here, and mention other relevant information

style-loader Supported?

Documentation Is:

  • Missing
  • Needed
  • Confusing
  • Not Sure?

Please Explain in Detail...

I am unsure if this plugin supports style-loader. In my attempts to get it working, I have not seen any differences between using this plugin and not using it; however, I am unsure if this is my fault or because the plugin does not support it.

Your Proposal for Changes

Document whether this plugin works for style-loader or if it requires something like mini-css-extract-plugin.

css-minimizer-webpack-plugin asking for postcss peer dependency when I'm not using postcss

  • Operating System: OSX 10.15.7
  • Node Version: 12.16.3
  • NPM Version: 6.14.11
  • webpack Version: 5.44.0
  • css-minimizer-webpack-plugin Version: 3.0.2

Expected Behavior

It should build the library for production environment

Actual Behavior

It's breaking the build due to the lack of postcss dependency which I don't need as I don't use any postcss:

ERROR in federated/components/index.acf1294b0dba07ff0d0c.css
federated/components/index.acf1294b0dba07ff0d0c.css from Css Minimizer
Error: PostCSS plugin postcss-discard-comments requires PostCSS 8.
Migration guide for end-users:
https://github.com/postcss/postcss/wiki/PostCSS-8-for-end-users

Code

https://gist.github.com/testacode/f1452bfb2c906270b9325ef34be6ca8e => webpack.base
https://gist.github.com/testacode/8efb09eba940e7ca6ea6738c2b86c15f => webpack.prod

How Do We Reproduce?

just build the library for prod env.

Hash output asset.css does not change

  • Operating System: Ubuntu
  • Node Version: 12.16.1
  • NPM Version: 6.14.7
  • webpack Version: 4 / 5
  • css-minimizer-webpack-plugin Version: 1.0.0

Expected Behavior

  1. Run webpack with the provided config
  2. Get output asset entry.40909804e9379fa0a37f.css
  3. Change minimizerOptions
  4. Run webpack
  5. Get output asset entry.other_hash.css

Actual Behavior

  1. Run webpack with the provided config
  2. Get output asset entry.40909804e9379fa0a37f.css
  3. Change minimizerOptions
  4. Run webpack
  5. Get output asset entry.40909804e9379fa0a37f.css

Hash does not change.

Code

module.exports = {
  ...
  module: {
    loaders: [
      {
        test: /.s?css$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
      },
    ],
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: '[name].[contentHash].css',
      chunkFilename: '[id].[name].[contentHash].css',
    }),
  ],
  optimization: {
    minimize: true,
    minimizer: [
      new CssMinimizerPlugin({
        minimizerOptions: {
          // When we change these options, the hash of the asset should also change
          preset: ['default', { discardEmpty: false }],
        },
      })
    ],
  },
};

Minified file contains 2 links to source map

  • Operating System: Ubuntu 20.10 (WSL in Windows 10)
  • Node Version: 14.16.0
  • NPM Version: 6.2.5 (Using PNPM, not NPM)
  • webpack Version: 5.36.2
  • css-minimizer-webpack-plugin Version: 2.0.0

Expected Behavior

There should be a line with a link to source map location at the end of the file.

Actual Behavior

There are 2 of said line, for some reason. The only difference between them is a space before the ending */

Code

https://gist.github.com/hyoretsu/d159f10cbee83a47d92a9789ac8bc4ef

How Do We Reproduce?

Just import any CSS with the linked config and there should be 2 links in minified file.

[DEP_WEBPACK_COMPILATION_OPTIMIZE_CHUNK_ASSETS] DeprecationWarning: optimizeChunkAssets is deprecated

  • Operating System: Windows 10
  • Node Version: 14.15.5
  • NPM Version: 6.14.11
  • webpack Version: 5.24.2
  • css-minimizer-webpack-plugin Version: 1.2.0

Expected Behavior

Webpack build should produce no deprecation warnings relating to css-minimizer-webpack-plugin

Actual Behavior

Following deprecation notice logged in console:

(node:21104) [DEP_WEBPACK_COMPILATION_OPTIMIZE_CHUNK_ASSETS] DeprecationWarning: optimizeChunkAssets is deprecated (use Compilation.hooks.processAssets instead and use one of Compilation.PROCESS_ASSETS_STAGE_* as stage option)

This is traceable back to the css-minimizer-webpack-plugin by running:

node --trace-deprecation node_modules/webpack/bin/webpack.js

Code

Relevant snippets from webpack.config.js

optimization: {
    minimize: true,
    minimizer: [new OptimizeCSSAssetsPlugin({}), new TerserPlugin()],
    splitChunks: {
      chunks: 'all',
    }
  },

How Do We Reproduce?

I see the warning message whenever running webpack build with the plugin enabled

Adjust the config of minify

Modification Proposal

I want to know if change the minify way from function to a string ?

Expected Behavior / Situation

just write as:

minify: '@parcel/css'

Actual Behavior / Situation

minify: CssMinimizerPlugin.parcelCssMinify,

I think it's more convenient.

TypeError [ERR_INVALID_URL]: Invalid URL: /8b43027f47b20503057dfbbaa9401fef.eot?#iefix&v=4.7.0

Issue occurs with [email protected] and [email protected].

Same issue also occurs with [email protected], but not 5.x. But perhaps that's expected since that plugin says to use css-minimizer-webpack-plugin instead when using [email protected].

 ERROR in 945.css
[2] 945.css from Css Minimizer
[2] TypeError [ERR_INVALID_URL]: Invalid URL: /8b43027f47b20503057dfbbaa9401fef.eot?#iefix&v=4.7.0
[2]     at /home/me/Documents/MyProject/945.css:10:3
[2]     at onParseError (internal/url.js:257:9)
[2]     at new URL (internal/url.js:333:5)
[2]     at /home/me/Documents/MyProject/node_modules/css-minimizer-webpack-plugin/node_modules/postcss-svgo/dist/index.js:32:17
[2]     at walk (/home/me/Documents/MyProject/node_modules/postcss-value-parser/lib/walk.js:7:16)
[2]     at ValueParser.walk (/home/me/Documents/MyProject/node_modules/postcss-value-parser/lib/index.js:18:3)
[2]     at minify (/home/me/Documents/MyProject/node_modules/css-minimizer-webpack-plugin/node_modules/postcss-svgo/dist/index.js:22:23)
[2]     at /home/me/Documents/MyProject/node_modules/css-minimizer-webpack-plugin/node_modules/postcss-svgo/dist/index.js:116:9
[2]     at /home/me/Documents/MyProject/node_modules/css-minimizer-webpack-plugin/node_modules/postcss/lib/container.js:91:18
[2]     at /home/me/Documents/MyProject/node_modules/css-minimizer-webpack-plugin/node_modules/postcss/lib/container.js:74:18
[2]     at AtRule.each (/home/me/Documents/MyProject/node_modules/css-minimizer-webpack-plugin/node_modules/postcss/lib/container.js:60:16)

Typescript support

Feature Proposal

This package should come with official typescript support as Webpack 5 has official typescript support. Considering this is in webpack-contrib and listed (and used) on the official webpack documentation, it should have full support for the latest webpack-version if you're using webpack.config.ts.

Although there is a @types/ package for this, it's not being kept up-to-date so it breaks every few webpack versions (like it is currently broken for a few months). This effectively prevents typescript users of this plugin from updating webpack.

Feature Use Case

Using in webpack.config.ts with latest webpack version instead of having to wait multiple months for the DT package to get updated.

Please paste the results of npx webpack-cli info here, and mention other relevant information

System:
    OS: Linux 5.11 elementary OS 6 Odin
    CPU: (12) x64 Intel(R) Core(TM) i7-8700K CPU @ 3.70GHz
    Memory: 28.42 GB / 46.99 GB
  Binaries:
    Node: 17.1.0 - ~/.nvm/versions/node/v17.1.0/bin/node
    Yarn: 3.1.0 - ~/.nvm/versions/node/v17.1.0/bin/yarn
    npm: 8.1.2 - ~/.nvm/versions/node/v17.1.0/bin/npm
  Browsers:
    Chrome: 96.0.4664.45
    Firefox: 94.0
  Packages:
    babel-loader: ^8.2.3 => 8.2.3 
    css-loader: ^6.5.1 => 6.5.1 
    css-minimizer-webpack-plugin: ^3.1.4 => 3.1.4 
    eslint-import-resolver-webpack: ^0.13.2 => 0.13.2 
    fork-ts-checker-webpack-plugin: ^6.4.2 => 6.4.2 
    html-inline-script-webpack-plugin: ^2.0.3 => 2.0.3 
    html-webpack-plugin: ^5.5.0 => 5.5.0 
    postcss-loader: ^6.2.0 => 6.2.0 
    style-loader: 3.3.1 => 3.3.1 
    terser-webpack-plugin: ^5.2.5 => 5.2.5 
    webpack: 5.64.2 => 5.64.2 
    webpack-bundle-analyzer: ^4.5.0 => 4.5.0 
    webpack-cli: ^4.9.1 => 4.9.1 
    webpack-dev-server: ^4.5.0 => 4.5.0 
    webpack-manifest-plugin: 4.0.2 => 4.0.2

See also: DefinitelyTyped/DefinitelyTyped#49354 (comment)

esbuild: warnings are not visible

Hi,

Platform

  • Webpack: 5.62.1
  • css-minimizer-webpack-plugin : 3.1.1
  • node.js v16.11.0

I am using esbuild to minify the css

new CssMinimizerPlugin({
        minify: CssMinimizerPlugin.esbuildMinify,
        minimizerOptions: {
          legalComments: 'none',        
        },
      }),

Current behavior

Showing as [object object]
before-fix

Expected

Must show actual message
after-fix

Possible fix in this line

https://github.com/webpack-contrib/css-minimizer-webpack-plugin/blob/master/src/utils.js#L162

warnings: result.warnings
      ? result.warnings.map((item) => item.text)
      : [],

The same issue could be in terser-webpack-plugin

Calculations lose the required parentheses

Bug report

Actual Behavior

In my project i have index.css:

html {
  --dot-size: 6;
}

body {
  transform: scale(calc(1 / (10 / var(--dot-size))));
}

and index.js

import './index.css';

console.log('Hello, world!');

And webpack config:

const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');

module.exports = {
  mode: 'development',
  entry: './src/index.js',
  output: {
    filename: 'index.js',
    path: path.resolve(__dirname, 'dist'),
  },
  plugins: [new MiniCssExtractPlugin()],
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: [MiniCssExtractPlugin.loader, 'css-loader'],
      },
    ],
  },
  optimization: {
    minimize: true,
    minimizer: [
      '...',
      new CssMinimizerPlugin(),
    ],
  },
};

After run webpack, in dist folder i have css file with content:

/* ... */
body{transform: scale(calc(1/10/var(--dot-size)))}

Here the calc function has lost the necessary parentheses around the second division:

1 / (10 / 6) >>> 1 / 10 / 6

Looks like it is not a cssnano issue, here is a demo in playground with default preset:
https://cssnano.co/playground#eyJpbnB1dCI6ImJvZHkge1xuICAgIC0tZG90LXNpemU6IDY7XG4gICAgdHJhbnNmb3JtOiB0cmFuc2xhdGUzZCgtNTAlLC01MCUsMCkgc2NhbGUoY2FsYygxLygxMC92YXIoLS1kb3Qtc2l6ZSkpKSk7XG59IiwiY29uZmlnIjoie1xuICBcInByZXNldFwiIDogXCJkZWZhdWx0XCJcbn1cbiJ9

Expected Behavior

Required parens should not be omitted.

How Do We Reproduce?

For reproduce you can use code from previous sections.

Repo with example also here:
https://github.com/krutoo/css-minimizer-webpack-plugin-tests

Please paste the results of npx webpack-cli info here, and mention other relevant information

  System:
    OS: macOS 11.6
    CPU: (4) x64 Intel(R) Core(TM) i5-4258U CPU @ 2.40GHz
    Memory: 37.06 MB / 4.00 GB
  Binaries:
    Node: 14.17.0 - ~/.nvm/versions/node/v14.17.0/bin/node
    Yarn: 1.22.10 - ~/.nvm/versions/node/v14.17.0/bin/yarn
    npm: 7.13.0 - ~/.nvm/versions/node/v14.17.0/bin/npm
  Browsers:
    Chrome: 95.0.4638.69
    Firefox: 93.0
    Safari: 15.0
  Packages:
    css-loader: ^6.5.1 => 6.5.1
    css-minimizer-webpack-plugin: ^3.1.4 => 3.1.4
    webpack: ^5.64.1 => 5.64.1
    webpack-cli: ^4.9.1 => 4.9.1

Border width with two values compiled into tree values

  • Operating System: Linux 5.10
  • Node Version: v10.23.2
  • NPM Version: 6.14.11
  • webpack Version: 5.23.0
  • css-minimizer-webpack-plugin Version: ^1.2.0

I try to optimize some border options and use of border-width with two values: border-width: 13px 6px;
cssnano (css-minimizer-webpack-plugin) showed me strange and incorrect result: border-width: 13 6px 6px;

That strange optimization work only with exists all of three style-rules: border-width, border-style, border-right-color

Source:

div {
    border-width: 13px 6px;
    border-style: solid;
    border-right-color: transparent;
}

Expected Behavior

div{border-width:13px 6px;border-right:6px transparent;border-style:solid}

Actual Behavior

div{border-width:13px 6px 6px;border-right:6px transparent;border-style:solid}

Code

https://gist.github.com/dimti/468b3793ec81d7c5b1f0f1e1669c2eb1

How Do We Reproduce?

Source styles:

div {
    border-width: 13px 6px;
    border-style: solid;
    border-right-color: transparent;
}

I set horizontal padding to 13px and vertical padding to 6px with appropriate this tutorial https://developer.mozilla.org/ru/docs/Web/CSS/border-width#%D1%81%D0%B8%D0%BD%D1%82%D0%B0%D0%BA%D1%81

Compiled data without optimizations - show me correct result: border-width: 13px 6px;

With optimization i'm have incorrect result: border-width: 13px 6px 6px;

[WONTFIX] v3.4.1 npm audit fail -> Severity: moderate; need postcss v>=8.4.6

yarn -v
	3.2.0

yarnlist | egrep "nanoid|postcss@| css-loader|css-minimizer" | sort
	├─ css-loader@npm:6.6.0
	├─ css-minimizer-webpack-plugin@npm:3.4.1
	├─ nanoid@npm:3.3.1
	├─ postcss@npm:8.4.6

yarn npm audit --recursive
	└─ nanoid: 3.1.30
	   ├─ Issue: Exposure of Sensitive Information to an Unauthorized Actor in nanoid
	   ├─ URL: https://github.com/advisories/GHSA-qrpm-p2h7-hrv2
	   ├─ Severity: moderate
	   ├─ Vulnerable Versions: <3.1.31
	   ├─ Patched Versions: >=3.1.31
	   ├─ Via: nanoid, postcss, css-loader, css-minimizer-webpack-plugin
	   └─ Recommendation: Upgrade to version 3.1.31 or later

yarn why nanoid
	├─ test.app@workspace:.
	│  └─ nanoid@npm:3.3.1 (via npm:^3.3.1)
	│
	├─ postcss@npm:8.4.5
	│  └─ nanoid@npm:3.1.30 (via npm:^3.1.30)
	│
	└─ postcss@npm:8.4.6
	   └─ nanoid@npm:3.2.0 (via npm:^3.2.0)

yarn why postcss
	├─ css-loader@npm:6.6.0
	│  └─ postcss@npm:8.4.5 (via npm:^8.4.5)
	│
	├─ css-loader@npm:6.6.0 [62071]
	│  └─ postcss@npm:8.4.5 (via npm:^8.4.5)
	│
	├─ css-minimizer-webpack-plugin@npm:3.4.1
	│  └─ postcss@npm:8.4.5 (via npm:^8.3.5)
	│
	├─ css-minimizer-webpack-plugin@npm:3.4.1 [62071]
	│  └─ postcss@npm:8.4.5 (via npm:^8.3.5)
	...

@css-loader
https://github.com/webpack-contrib/css-loader/blob/4dede5553f981dc87931de996b47f7036a883e5d/package.json#L46

-	    "postcss": "^8.4.5",
+	    "postcss": "^8.4.6",

@css-minimizer-webpack-plugin

"postcss": "^8.3.5",

-	    "postcss": "^8.3.5",
+	    "postcss": "^8.4.6",

[webpack5]Run with warning output

  • Operating System: MacOS
  • Node Version: v15.4.0
  • NPM Version: v7.0.15
  • webpack Version: v5.19.0
  • css-minimizer-webpack-plugin Version: v1.2.0

Expected Behavior

Run without warning

Actual Behavior

(node:8056) [DEP_WEBPACK_COMPILATION_OPTIMIZE_CHUNK_ASSETS] DeprecationWarning: optimizeChunkAssets is deprecated (use Compilation.hook.processAssets instead and use one of Compilation.PROCESS_ASSETS_STAGE_* as stage option)
(node:9741) [DEP_WEBPACK_COMPILATION_ASSETS] DeprecationWarning: Compilation.assets will be frozen in future, all modifications are deprecated.
BREAKING CHANGE: No more changes should happen to Compilation.assets after sealing the Compilation.
        Do changes to assets earlier, e. g. in Compilation.hooks.processAssets.
        Make sure to select an appropriate stage from Compilation.PROCESS_ASSETS_STAGE_*.

Code

// webpack.config.ts
import Config, { LoaderOptions } from 'webpack-chain';
import CssMinimizerPlugin from 'css-minimizer-webpack-plugin';

const config: Config = new Config();

// some code

config.optimization /// doc: https://webpack.js.org/configuration/optimization/
    .minimizer('css')
    .use(CssMinimizerPlugin)
    .end();

// some code

export default config.toConfig();

Production only error

Bug report

The plugin works in development but does not build for production.

Using:

"css-minimizer-webpack-plugin": "^3.1.4"
"webpack": "^5.11.0"
"webpack-cli": "4.6.0"
"webpack-dev-server": "^3.11.2"
"@rails/webpacker": "^6.0.0-beta.5",

Actual Behavior

Webpack was set up like this:

...
  optimization: {
    minimizer: [
      new CssMinimizerPlugin()
    ],
    minimize: true,
  },
...

Running ./bin/webpack --watch --progress results in minified CSS files in development with no errors.

Then I ran the command to bundle for production:
bundle exec rake assets:clean[9]; RAILS_ENV=production bundle exec rake assets:precompile

However, trying to compile for production does not work.

Expected Behavior

The expected behavior is for the plugin to work in both development and production.

How Do We Reproduce?

Please paste the results of npx webpack-cli info here, and mention other relevant information

Error message:

Invalid options object. Css Minimizer Plugin has been initialized using an options object that does not match the API schema.
 - options has an unknown property 'sourceMap'. These properties are valid:
   object { test?, include?, exclude?, minimizerOptions?, parallel?, warningsFilter?, minify? }

In order to get it to work I had to downgrade to "css-minimizer-webpack-plugin": "^1.3.0" but ideally I could use the latest version.

TY!

output multiple css-files

Hi there. How can i output 2 css-files - in my case a main.css (wordpress frontend) and editor.css (wordpress backend)? Currently i'am outputting only the minified main.css.

Code below or https://github.com/MarkusHeinisch/wordpress-tailwind-boilerplate/blob/main/assets/webpack.config.js

`const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const CopyPlugin = require('copy-webpack-plugin');

const SRC = 'src';
const JS_DIR = path.resolve(__dirname, SRC + '/js');
const IMAGE_DIR = path.resolve(__dirname, SRC + '/images');
const FONT_DIR = path.resolve(__dirname, SRC + '/fonts');
const OUTPUT_DIR = path.resolve(__dirname, 'out');

module.exports = {
entry: {
main: JS_DIR + '/main.js',
editor: JS_DIR + '/editor.js',
},
output: {
path: OUTPUT_DIR,
filename: 'js/[name].js',
clean: true,
},
plugins: [
new MiniCssExtractPlugin({
filename: 'css/[name].css',
}),
new CopyPlugin({
patterns: [
{
from: IMAGE_DIR,
to: 'images/[name][ext]',
},
{
from: FONT_DIR,
to: 'fonts/[name][ext]',
},
],
}),
],
module: {
rules: [
{
test: /.(s[ac]|c)ss$/i,
exclude: /node_modules/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'postcss-loader',
'sass-loader',
],
},
],
},
optimization: {
minimizer: [..., new CssMinimizerPlugin()],
},
externals: {
jquery: 'jQuery',
},
};
`

Hash output with css modules produce NaN in animation-name when using @keyframe

When using css module features, and using @Keyframes, some keyframes name produce an invalid hash in the related css animation name.

.signature {
  width: 80px;

  path {
    animation: draw 3.3s ease-in-out forwards;
    stroke: #fff;
    stroke-dasharray: 450;
    stroke-dashoffset: 450;
  }

  circle {
    animation: draw-circle 0.25s ease-in 1.5s forwards;
  }
}

@keyframes draw {
  to {
    stroke-dashoffset: 0;
  }
}

@keyframes draw-circle {
  from {
    fill: #fff;
    opacity: 0;
  }

  to {
    fill: #fff;
    opacity: 1;
  }
}

is producing this :

._2f-763U9aR_m95TZkSTerd{width:80px}._2f-763U9aR_m95TZkSTerd path{animation:NaNjtcXwnmOr8f36q3l-8W 3.3s ease-in-out forwards;stroke:#fff;stroke-dasharray:450;stroke-dashoffset:450}._2f-763U9aR_m95TZkSTerd circle{animation:_2APW8yWcYXdDHglJ5UTsYC .25s ease-in 1.5s forwards}@keyframes e5jtcXwnmOr8f36q3l-8W{to{stroke-dashoffset:0}}@keyframes _2APW8yWcYXdDHglJ5UTsYC{0%{fill:#fff;opacity:0}to{fill:#fff;opacity:1}}

Note the animation:NaNjtcXwnmOr8f36q3l-8W. Should be animation:e5jtcXwnmOr8f36q3l-8W.

  • When i do not use css-minimizer-webpack-plugin, the bug disapear.

  • When i rename the keyframe's name from draw to draw-path for exemple, this is working well with css-minimizer-webpack-plugin.

I don't think it's a cssnano issue, because i'm using cssnano preset default as well with postcss-loader.

You can reproduce by following this steps in this repo :

  1. Follow this steps to add the src/images/signature.svg to home view
  2. Just make a production build : npm run build
  3. Launch the production server: npm run start:prod

See build/css/home.css result. Webpack configuration are in config/webpack

  • Operating System: MacOSX Catalina 10.15.5
  • Node Version: 12.18.3
  • NPM Version: 6.14.8
  • webpack Version: 4.44.2
  • css-minimizer-webpack-plugin Version: 1.1.4

Issue already asked in css-loader repository : webpack-contrib/css-loader#1200 and webpack repository : webpack/webpack#11568

Hangs indefinitely when used as drop-in replacement for optimize-css-assets-webpack-plugin

Bug report

Actual Behavior

Most builds execute fine, although the output is not as small as with optimize-css-assets-webpack-plugin - but at least one of our builds hangs indefinitely. It's an expected 2.5mb output file, but even with parallel: true the build failed to complete after 10 minutes, whereas it usually takes about 2 minutes, 3 tops with optimize-css-assets-webpack-plugin

Expected Behavior

No hanging builds. Processor core is maxed out for the duration of the build, but no output is ever produced.

How Do We Reproduce?

I wish I knew.

Our minimizer config looks like this for a failing build:

    new TerserPlugin({
      parallel: 2,
      terserOptions: {
        ecma: 8,
        toplevel: true,
        mangle: {
          toplevel: true,
        },
        compress: {
          toplevel: true,
          warnings: true,
        },
      },
    }),
    new CssMinimizerPlugin(),

And on a working build:

new TerserPlugin({
  parallel: 2,
  terserOptions: {
    ecma: 2021,
    mangle: true,
    compress: {
      toplevel: true,
      warnings: true,
      drop_console: true,
      drop_debugger: false,
    },
  }
}),
new CssMinimizerPlugin(),

Please paste the results of npx webpack-cli info here, and mention other relevant information

webpack 5.74.0 compiled with 32 errors and 2 warnings in 4060 ms

  System:
    OS: Windows 7 6.1.7601
    CPU: (4) x64 AMD Ryzen 7 5800X 8-Core Processor
    Memory: 7.38 GB / 14.00 GB
  Binaries:
    Node: 16.16.0 - ~\AppData\Roaming\npm\node.EXE
    Yarn: 1.22.19 - C:\Program Files (x86)\Yarn\bin\yarn.CMD
    npm: 8.11.0 - ~\AppData\Roaming\npm\npm.CMD
  Browsers:
    Chrome: 104.0.5112.81
    Internet Explorer: 11.0.9600.19597

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.