Webpack hooks and ng watch

Ryan Hoffnan
ITNEXT
Published in
3 min readOct 17, 2021

--

“watch” is something we take for granted in our development cycle.
with each file change or save our app rebuilds/re-renders it self and we see the latest version. But there is a catch. the build command never ends…. and thats annoying.

if you ever tried to this before:

ng build --watch && node test.js

And got angry that your test.js never actually got to run, its because of that small watch flag we gave to the ng build. It tell angular to keep the process and listen to all file changes ( or the types of files we told it to listen to).

In my use case I needed to add a config file to the dist folder after the build and any solution I tried (run-all, concurrently, postbuild ) failed because of timing mismatches between the commands. and forced me to run it manually after each save. ( not the best practice)
And than… , when all hope was gone I found this:

Webpack hooks.

We have this file we don’t like to touch, webpack.config.js , it is scary and most of us don’t know how it works, it’s a given from the whatever cli command we used to create our application. A true “black box”. So how does Angular uses the webpack.config.js file.

In our Angular.json file in the root of our project we have the option to pass a custom webpack config to each application/library in our project folder.

"build": {
"builder": "@angular-builders/custom-webpack:browser",
"options": {
"customWebpackConfig": {
"path": "./custom-webpack.config.js"
},

Angular compiler in build time will run the config file we give it with the original webpack config passed into it .
This allows us to extend or/and override the config as we want (unless we break webpack). See example below

In this example I add a functionality to the “done” hook of webpack which runs each time it finished its cycle (in our case a ng build cycle), a list of all the webpack hooks available can be found here.

The behavior in the example above will run “npm run add:file” each time webpack is done rebuilding my angular project.

This is just a small example of what can be done with webpack config. I was happy to find this tweak which solved a real problem for my team, and gave us a much smoother development experience.
Unfortunately and fortunately, Webpack does a lot of black-magic and its time that we try and learn to understand more about it, so we can use this powerful tool how we want and need.

--

--