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

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up