M
M
Michael R.2018-10-13 17:05:35
webpack
Michael R., 2018-10-13 17:05:35

Grouping (optimization) CSS classes and styles as output from WebPack 4?

Greetings!
I am compiling the project through webpack 4 and I get "semi-optimized" css as a result.

Excerpt from webpack.config.js
{
  test: /\.((s[ac]|c)ss)$/,
  use: [
    PLUGINS.mini_css_extract_plugin.loader,
    {
      loader: 'css-loader',
      options: {
        sourceMap: !isProduction
      }
    },

    {
      loader: 'postcss-loader',
      options: {
        ident: 'postcss',
        sourceMap: !isProduction,
        plugins: (() => {
          return isProduction ? [
            require('autoprefixer')({
              browsers: ['last 2 versions']
            }),
            require('cssnano')({
              preset: 'default'
            }),
            require("css-mqpacker")
          ] : []
        })()
      }
    },

    {
      loader: 'sass-loader',
      options: {
        outputStyle: 'expanded',
        sourceMap: !isProduction
      }
    },
  ]
},


1. Before building the project, I have the following scss code:
.class_1 {
  width: 1px;
}

.class_2 {
  width: 1px;
}

.class_3 {
  width: 2px;
}

2. After assembly, I have the following output:
.class_1, .class_2 {
  width: 1px
}

.class_3 {
  width: 2px
}

It seems that everything is fine and the classes have been optimized, BUT! We are trying to change the sequence of classes in scss and start the build again...
3. Before building the project, I have the following scss code (changed class_2 and class_3):
.class_1 {
  width: 1px;
}

.class_3 {
  width: 2px;
}

.class_2 {
  width: 1px;
}

4. After assembly, I have the following output:
.class_1 {
  width: 1px
}

.class_3 {
  width: 2px
}

.class_2 {
  width: 1px
}

I would like to optimize all classes, and not just those that go exclusively one after another.
Can you tell me the plugin (and its settings) to combine class names if they have the same styles?
Thank you!
UPD:
Due to the fact that many people are worried about width: 2px; - replace it with color: red;
At the entrance:
.class_1 {
  width: 1px;
}

.class_3 {
  color: red;
}

.class_2 {
  width: 1px;
}

At the exit:
.class_1 {
  width: 1px
}

.class_3 {
  color: red
}

.class_2 {
  width: 1px
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
alex, 2018-10-13
@Mike_Ro

I would like to optimize all classes
this is not called optimization, but “I don’t understand what’s going on”
before “optimization” after “optimization” (which you expect) the width will break, because class_2 will go up: so there is no error here, everything is ok, your optimizer works fine.

A
ar5, 2018-10-13
@ar5

Try this plugin https://github.com/NMFR/optimize-css-assets-webpac...
Optimizes the final build. Under the hood is the same cssnano

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question