statianzo / webpack-livereload-plugin

LiveReload during webpack --watch
ISC License
204 stars 51 forks source link

Add option to watch for changes on other files in the project #79

Closed hirasso closed 2 years ago

hirasso commented 2 years ago

Hi there! I am using this plugin in a classic server-side rendered environment based on php. Having the browser reload when I edit my js and scss files is great, but the gold standard for me is to also have the browser reload if I change my php files.

I was able to hack something together that makes this possible through webpack-livereload-plugin. Following are the relevant partsin my webpack.config.js:

const LiveReloadPlugin = require('webpack-livereload-plugin')
const chokidar = require('chokidar');

/**
 * Live Reloading
 */
const initLiveReloadPlugin =() => {
  const options = {
    appendScriptTag: true,
  }
  const liveReloadPlugin = new LiveReloadPlugin(options)
  const reload = path => {
    // this goes through to tiny-lr that is being used by LiveReloadPlugin
    liveReloadPlugin.server.notifyClients(['index.php'])
  }
  // watch for changes to .php files and reload
  createFileWatcher('**/**.php')
    .on('change', reload)
    .on('unlink', reload)

  return liveReloadPlugin
}
/**
 * Get a file watcher 
 */
const createFileWatcher = files => {
  const watcher = chokidar.watch(files, {
    ignored: ['node_modules', 'vendor'], 
    ignoreInitial: true,
    followSymlinks: false,
    atomic: false
  })
  return watcher;
}

let config = {
  // My webpack config object...
}

/**
 * Adjusts the config depending on the --mode
 * @see https://webpack.js.org/configuration/mode/
 * @param {object} env  set via --env flag
 * @param {object} argv 
 * @returns 
 */
module.exports = (env, argv) => {
  if (argv.mode === 'development') {
    // here I am injecting the plugin if in dev mode
    config.plugins.push(initLiveReloadPlugin())
  }
  return config;
};

So as you can see, I am starting a chokidar watcher and when I change any of my php files, I send a request through webpack-livereload-plugin to tiny-lr to reload the page.

I can imagine many other people like me would enjoy this kind of functionality. Maybe it could become a part of this plugin? As an additional option, for example watchAdditionalFiles or the like?

statianzo commented 2 years ago

@hirasso Would something like this work? https://github.com/pigcan/extra-watch-webpack-plugin It appears to add files to Webpack's file tracking. Assuming it works, changes to those files should be passed into this plugin as well.

hirasso commented 2 years ago

@statianzo extra-watch-webpack-plugin can indeed watch my php files and re-compile if I save them, but it doesn't trigger your livereload script to reload my browser.