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

Leo*_*ang 13 javascript reactjs webpack babeljs

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"
        }
    },
Run Code Online (Sandbox Code Playgroud)

Then, it's used in React:

return t(r, {
    onInput: o(this, "str"),
    class: a.a.textarea
})
Run Code Online (Sandbox Code Playgroud)

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"
})
Run Code Online (Sandbox Code Playgroud)

Is this possible?

小智 1

我分享了我在生产中使用的 WEBPACK 配置,它使用 PURGECSS 来删除未使用的类,就像您可以包含未编译的选择器一样。

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 }),
    }),
  ],
});

Run Code Online (Sandbox Code Playgroud)

希望能帮助到你。