Search code examples
webpackwebpack-dev-serverwebpack-2

webpack dev server: watch arbitrary directory files and reload


Is it possible to make webpack-dev-server reload whenever a specified set of arbitrary files changes?

Something along the lines of:

devServer: {
    watchTheseFiles: [ 'path/to/files', 'path/to/more/files' ]
}

And even more granularly, can I specify a regex of which files to watch?

I'm doing this as a bit of a hack to reload when I trigger certain changes in arbitrary files (they could be .txt, .png, whatever...)

At the moment, the specified paths in contentBase don't seem to trigger reload when files change.


Solution

  • I'm not sure if there's anything readily available that's better than contentBase. webpack, webpack-dev-server and webpack-dev-middleware all expose an invalidate(callback) helper, but it would require you to create your custom script to programmatically manage the compiler, server or middleware to invoke the handler.

    Something similar to this that should work across all compilers configured for watching is to add additional files as compilation dependencies and let webpack handle the invalidation. You can also do this when using webpack programmatically, but it's also really easy to write your own plugin and perform this from the configuration. Here's an example:

    class CustomContextPlugin {
        apply (compiler) {
            compiler.hooks.beforeCompile.tap('CustomContextPlugin', params => {
                params.compilationDependencies.add(
                    path.resolve(__dirname, 'public', 'robots.txt')
                )
            })
        }
    }
    
    module.exports = {
        plugins: [
            new CustomContextPlugin()
        ]
    }
    

    It uses the beforeCompile hook to add a robots.txt file as a compilation dependency. In development where we don't perform any caching, this should cause the development server to reload the page because new chunks were emitted.

    There's probably also other options. One thing that comes to mind is maybe having a development entry or some other module that uses require.context, but I think these options would involve more effort.