Optimizing your experience
WikipediaWikipedia
Gradient background

How to minify CSS files via CopyWebpackPlugin for Webpack5

Clarice Bouwer

Software Engineering Team Lead and Director of Cloudsure

Wednesday, 15 June 2022 · Estimated 1 minute read

Goal

Emit minified vendor-based CSS files on build.

Dependencies

package.json
Copy
"copy-webpack-plugin": "11.0.0",
"cssnano": "5.1.11",
"webpack": "5.70.0",
"webpack-cli": "4.9.2"

Elaborate

I have a few unminified vendor CSS files that I simply want to minify and copy to an output directory. These files were not being transformed by terser probably due to the chain of command (steps in which the build is processed).

All CSS files matching this regex /src/vendors/**/*.css are transformed using postcss and cssnano in conjunction with the CopyWebpackPlugin.

Code

webpage.config.js
Copy
...
plugins: [
  new CopyWebpackPlugin({
    patterns: [
      {
        from: 'src/vendors/**/*.css',
        to: './css/[name].[contenthash].min[ext]',
        transform: (content, path) => {
          return postcss([cssnano])
            .process(content, {
              from: path,
            })
            .then((result) => {
              return result.css;
            });
        },
      },
    ],
  }),
],
...