Tutorial for webpack 4 - part 10 - watching for changes

webpackWebpack is executed multiple times during standard development. Whenever I change an SCSS file, I have to run the whole webpack process to convert SCSS to CSS and bundle all resources. Until now I have been doing it by manually running npx webpack --mode=development. There is a better way - webpack can observe the source files and do it's job automatically.

 

Table of contents

If you want to jump to other parts of the tutorial, use table of contents.

 

Enable watching

Watching is an option of webpack. If you accept default settings, the easiest way to enable it is to set watch to true in webpack.config.js.

webpack.config.js
------------
...
module.exports = {
   
entry: {
       
races: "./main/webapp/scripts/races.js",
       
results: "./main/webapp/scripts/results.js",
    },
   
...
   
watch: true
};

 

Watching in action

Once I enabled watching, I start webpack:

npx webpack --mode=development

I open races.html.

before changes

Now, I make a change in the source code. I even pick an SCSS variable as it requires building CSS files first. I go to _variables.scss and change the background color from azure to green:

$margin-background-color: green;

Then I refresh the races.html without rerunning webpack.

after changes

It is green now.

When you take a look at the Terminal/Windows CMD, you should see that webpack noticed the change and repacked the bundle.

I encourage you to experiment with it. It works with all resources handled by webpack.

 

Advanced watch options

The default settings are good enough for most cases. But if you are not satisfied with the standard behavior, there are some ways to customize it.

 module.exports = {
   
...
   
watch: true,
   
watchOptions: {
        
aggregateTimeout: 1000,
       
poll: 2000,
       
ignored: ['sounds/**/*.wav', 'node_modules']
    }
};
poll - how often files are checked for changes; the value is provided in milliseconds 
aggregateTimeout - how long webpack should wait after noticing a change before it starts rebuilding a package
ignored - files that are not watched for changes

 

Summary

This article showed how to automate rebuilding a package 

Source code created in this part is on tutorial/part10-watching-for-changes branch on GitHub.

 

Next part

Tutorial for webpack 4 - part 11 - external JS library (jquery-ui)