size-plugin icon indicating copy to clipboard operation
size-plugin copied to clipboard

Ability for a custom function using sizes

Open guillermodlpa opened this issue 5 years ago • 0 comments
trafficstars

Hi there 👋

I'm trying to create a plugin that calculates file sizes of all bundles and then pushes those stats to a custom data store, Firebase Cloud Firestore in my case. So I've looked into reusing this plugin.

One approach would be to create a new plugin that extends SizePlugin, overriding the apply method to not print to console, and instead use this.sizes as I see fit. Somethingl ik

export default class MyCustomSizePlugin extends SizePlugin {
    async apply(compiler) {
        const outputPath = compiler.options.output.path;
        this.output = compiler.options.output;

        const afterEmit = (compilation, callback) => {
            this.load(outputPath)
                .then((sizes)=> {
                    /* do what I need to do with sizes */
                })
                .catch(console.error)
                .then(callback);
        };

        /* ... */
    }
}

Note: the example above doesn't work fully as expected, still haven't figured out why, but I imagine it's possible to make it work.

Another approach I like more is to add a new feature to size-plugin to offer a custom callback. This way, we keep pretty printing as well as offer the ability for developers to do any additional operations with the calculated sizes. It could look like this:

// in webpack config
plugins: [
  SizePlugin({
    onSizesCalculated: (sizes) => { /* custom handling of the bundle sizes */ },
  }),
],

The code change required would likely be minimal, probably:

if (this.options.onSizesCalculated) {
    this.options.onSizesCalculated(Object.assign({}, this.sizes});
}

For context, the this.sizes object of the plugin looks like this:

{
    'bundle.js': 1070,
    '1.*****.chunk.js': 102,
    '2.*****.chunk.js': 137,
}

How do these ideas sound? Am I over-complicating myself and there's a simpler way to solve my problem without using size-plugin? Or does the idea of adding a custom callback sound valuable? I'd be happy to open PR if that's the case.

guillermodlpa avatar May 02 '20 14:05 guillermodlpa