🐏 Webpack RAM plugin
In order to fine-tune the builds of your frontend applications, you need to concentrate on analysis of the build process. One of such criteria is the usage of your system resources. To be able to find the usage of your memory during the build, DeCODE have created a webpack plugin, which injects to your build system and then sends the report to your terminal
Webpack hooks system
Based on the official webpack documentation, plugin needs to define, which hooks
it needs to inject to.
In this exact scenario, it was necessary to get analysis of RAM after webpack finished it's compilation, so
hooks done
and failed
were used.
class WebpackMemoryPlugin {
apply(compiler) {
compiler.hooks.failed.tap(
'WebpackMemoryPlugin',
() => {
const used = process.memoryUsage().heapUsed / 1024 / 1024;
console.log(`🐏 Amount of RAM used: ${Math.round(used * 100) / 100} MB`);
}
);
compiler.hooks.done.tap(
'WebpackMemoryPlugin',
() => {
const used = process.memoryUsage().heapUsed / 1024 / 1024;
console.log(`🐏 Amount of RAM used: ${Math.round(used * 100) / 100} MB`);
}
);
}
}
Testing of webpack plugin
To make sure that the plugin works as expected, it was covered with unit test.
In this case, unit testing was implemented with mocha
and sinon
.
Because the plugin by itself is quite simple, and just outputs the amount of RAM
to the console, it can be done by spying on the console and verified by just
checking the expected output.
const webpack = require('webpack');
const WebpackMemoryPlugin = require('../WebpackMemoryPlugin');
const sinon = require('sinon');
const assert = require('assert');
describe('WebpackMemoryPlugin', () => {
it('should show the amount of RAM used after success', (done) => {
let spy = sinon.spy(console, 'log');
webpack({
plugins: [
new WebpackMemoryPlugin()
],
}, (err, stats) => {
try {
spy.restore();
assert(spy.called);
assert(spy.firstCall.firstArg.indexOf('🐏 Amount of RAM used:') !== -1);
done();
} catch (ex) {
spy.restore();
console.log(ex);
done(ex);
}
});
});
});
Full code can be found at https://github.com/FallenAngel97/webpack-memory-plugin