Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to combine Webpack modules to decrease file size?

I'm using CSS modules, so a lot of the modules Webpack generates look like this:

    124: function(t, e, n) {
        t.exports = {
            textarea: "TextareaStyles__textarea"
        }
    },

Then, it's used in React:

return t(r, {
    onInput: o(this, "str"),
    class: a.a.textarea
})

It'll be smaller if Webpack combined the CSS module and React component into a single module. Then, Uglify/Terser can probably just make it inline:

return t(r, {
    onInput: o(this, "str"),
    class: "TextareaStyles__textarea"
})

Is this possible?

like image 370
Leo Jiang Avatar asked Jul 27 '19 07:07

Leo Jiang


1 Answers

I share the configuration of WEBPACK that I use in production, this uses PURGECSS to remove the classes that are not used, in the same way you can include selectors that are not being compiled.

const path = require('path');
const merge = require('webpack-merge');
const PurgecssPlugin = require('purgecss-webpack-plugin');
const glob = require('glob');
const TerserPlugin = require('terser-webpack-plugin');
const common = require('./webpack.common.js');

const PATHS = {
  src: path.join(__dirname, 'src'),
};

module.exports = merge(common, {
  mode: 'production',
  devtool: 'source-map',
  optimization: {
    minimizer: [new TerserPlugin({
      sourceMap: true,
    })],
  },
  plugins: [
    require('cssnano')({ preset: 'default' }),
    new PurgecssPlugin({
      whitelistPatternsChildren: [
        // Here we include a regex to force the included values
        /^btn-/i,
      ],
      paths: () => glob.sync(`${PATHS.src}/**/*`, { nodir: true }),
    }),
  ],
});

Hope it helps.

like image 121
joseluismurillorios Avatar answered Oct 06 '22 04:10

joseluismurillorios