How to write/upgrade your webpack plugin for adding support for webpack 4.

Harshwardhan Rathore
Frontend Weekly
Published in
2 min readDec 30, 2017

--

Webpack 4 alpha.2 is out and it’s time that your plugin supports webpack 4.

If you are new to writing webpack plugin, then please click here. This post require a basic knowledge of writing webpack plugin.

Done? Awesome, now that you have a basic understanding of how to write a webpack plugin from scratch lets start and see what has really changed in webpack 4 and what pieces you need to change to support webpack 4.

Remember the amazing HelloWorld plugin that we wrote here, we are going to make changes to the same file to support webpack 4.

The only piece the has changed in webpack 4 is how you plug into the Tapable instance.

Earlier(Webpack 3):

apply(compiler) {
compiler.plugin("done", () => {
console.log("Hello world");
})

Here we are listening the “done” event on the Tapable instance “compiler” using compiler.plugin("done", fn) where fn represents the function that you want to execute on the done event.

Webpack4 version:

apply(compiler) {
compiler.hooks.done.tap("HelloWorld", () => {
console.log("Hello world");
})

Here the compiler has the method named hooks on which we can chain the event name we want to listen to and then we are taping on this instance using .tap method.

The tap method expects two arguments, first one is of type string which should be the name of your plugin class which in our case is “HelloWorld” and second one is the function that we want to execute on “done” event.

That’s pretty much it, everything else in our plugin code remains the same. So after the above modification our final code for “HelloWorld” plugin should look like this.

class HelloWorld {
constructor(options) {
this.options = options;
}

apply(compiler) {
compiler.hooks.done.tap("HelloWorld", () => {
console.log(this.options.message);
})
}
module.exports = HelloWorld;

Let me know if you face any trouble in adding support for webpack 4.

Here is my webpack plugin after adding the support for webpack 4. Check out the same plugin for webpack 3 here.

Testing your new plugin.

For testing if your changes are working as expected you need to upgrade webpack in your app to 4.0.0-alpha.2 For this you need to do 2 things.

  1. Update you package.json file with the new version and run npm install
"webpack": "^4.0.0-alpha.2"

2. In the new webpack the webpack-cli has been moved to a different package so if you want to use webpack command in console, you need to add this package separately.

npm install --save-dev webpack-cli

Now your test app is ready for your upgraded plugin.

Thanks for reading. Please 👏 if you liked this post and let me know if you face any trouble in the process. I will be more than happy to help.

Follow me on Twitter and Github

--

--