DEV Community

Clarice Bouwer
Clarice Bouwer

Posted on

7 4

How to minify CSS files via CopyWebpackPlugin for Webpack5

Goal

Emit minified vendor-based CSS files on build.

Dependencies

"copy-webpack-plugin": "11.0.0",
"cssnano": "5.1.11",
"webpack": "5.70.0",
"webpack-cli": "4.9.2"
Enter fullscreen mode Exit fullscreen mode

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:

...
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;
            });
        },
      },
    ],
  }),
],
...
Enter fullscreen mode Exit fullscreen mode

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay