Home > Blockchain >  Webpack hot module replacement, how to configure watched directories
Webpack hot module replacement, how to configure watched directories

Time:06-30

I'm on webpack 5.x and webpack-dev-server 4.x and use hot module replacement. In certain cases, I want to watch an imported module from node_modules and use the hot module replacement on this as well.

I can't find how to configure the list of watched directories to add node_modules/<my module>

any help is appreciated

CodePudding user response:

This is controlled using Webpack Cache. You have to use the managedPath feature of the Webpack Cache. By default, it is set to ['node_modules']. It is now being migrated under snapshot object. The directory/file paths that you provide to this options tells Webpack that it is managed by a package manager like npm or yarn. Thus it can be considered constant and doesn't change meaning it can be cached by Webpack.

The only catch is that documentation says that it only takes array of string values (directory paths) and it doesn't support Regular Expressions and it is a allow-list (whitelist) instead of reject-list. So, if you have 100s of node_modules, you would have to read them using glob and then provide those all as strings of array except for the one that you want Webpack to watch.

const fs = require('fs');
const path = require('path');

const allModules = fs.readdirSync('./node_modules');

const managedPaths = allModules.filter((moduleDir) => {

  const moduleName = path.basename(moduleDir);

  return moduleName !== 'module-to-watch';
});


module.exports = {
  // ...other options
  snapshot: {
    managedPaths
  }
};

Update

Looking at the TypeScript declarations in the Webpack respository seem to suggest that it now accepts RegExp as value. However, it is not documented properly on Webpack.

  • Related