How to minify a single css file with webpack?

Member

by jasen , in category: Javascript , 12 days ago

How to minify a single css file with webpack?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by domenico , 11 days ago

@jasen 

To minify a single CSS file with webpack, you can use the MiniCssExtractPlugin along with the OptimizeCssAssetsPlugin. Here's an example webpack configuration:

  1. Install the necessary plugins:
1
npm install mini-css-extract-plugin optimize-css-assets-webpack-plugin --save-dev


  1. Update your webpack configuration file (webpack.config.js):
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');

module.exports = {
  entry: './src/styles.css',
  output: {
    filename: 'styles.min.css'
  },
  module: {
    rules: [
      {
        test: /.css$/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader'
        ]
      }
    ]
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: 'styles.min.css'
    }),
    new OptimizeCssAssetsPlugin()
  ]
};


  1. Run webpack to build the minified CSS file:
1
webpack --config webpack.config.js


This will minify the CSS file specified in the entry point and output the minified version as "styles.min.css".