Watch a directory with webpack

Viewed 1956

I have webpack installed in my development environment to bundle my dependencies. In addition, I am using the webpack-merge-and-include-globally plugin to concatenate a bunch of js files and include in a script tag in the markup.

When I run webpack with the --watch flag, it watches my entry file (build/index.js) but I would also like it to watch all the files in the /build/ directory and any files or directories I place inside it - a "deep watch" of sorts.

How can I setup webpack to --watch an arbitrary directory, not associated with my entry file?

webpack.config.js

const path = require('path');
const TerserPlugin = require("terser-webpack-plugin");
const merge = require('webpack-merge-and-include-globally');

module.exports = {
    entry: "./build/index.js",
    module: {
        rules: [
            {
                test: /\.s[ac]ss$/i,
                use: [
                    "style-loader",
                    "css-loader",
                    "sass-loader",
                ],
            },
        ],
    },
    output: {
        path: path.resolve(__dirname,'dist'),
        filename: 'bundle.js'
    },

    plugins: [
        new merge({
            files: {
                "./app.js" : [
                    './build/js/app.js',
                    './build/js/controllers/*',
                ],
            },
        }),
    ],

    optimization: {
        minimize: process.env.NODE_ENV === 'production',
        minimizer: [new TerserPlugin()]
    },

    mode: process.env.NODE_ENV === 'production' ? 'production' : 'development'

}
2 Answers

Try using this plugin:

import WatchExternalFilesPlugin from 'webpack-watch-files-plugin'

const config = {
  // ... webpack config ...
  plugins: [
    // ....
    new WatchExternalFilesPlugin({
      files: [
        './src/**/*.js',
        '!./src/*.test.js'
      ]
    })
  ]
}

Add watch: true to the config. This means after being built it will continue to build anytime any file is changed (and saved). Note you still need to initiate the first build

Related