how to run code when rollup watcher fires

Viewed 1400

Anyone know how to run code whenever the rollup watcher fires? I saw some references to trapping watcher events, like 'start', but I'm using a rollup.config.js file and I have no idea where and how I'd check for such events. FYI, I'm learning service workers and I want to modify the service worker file (appending a '\n' would be sufficient) whenever any of my source code changes.

2 Answers

On a separate forum, I received the following answer. It sounds correct to me, but I haven't implemented it yet so take it for what it's worth:

if you have your npm run dev command run node some-script.js and have some-script.js do something similar to https://rollupjs.org/guide/en/#rollupwatch then you can do a watcher.on('event' call and re-run w/e it is you want to run. you can use your existing config, and import it into some-script.js to pass as options to rollup.watch, with the addition of any watch specific options you'd like to add.

In many cases, the best way to do this is by writing a rollup plugin. Plugins have a watchChange callback that you can use to something when changes are detected. If you only want to do it when certain files change, you could use the minimatch library to check if the changed file matches a glob you pass in or configure somewhere.

This is a sketch of the solution I came up with:

function demoWatcherPlugin(globs) {
    let doTheAction = false

    return {
        watchChange(id) {
            // Does the file that just changed match one of the globs passed into
            // this plugin?
            const relPath = path.relative(__dirname, id)
            if (
                globs.some(
                    (item) => minimatch.match([relPath], item).length > 0
                )
            ) {
                doTheAction = true
            }
        },

        async buildEnd() {
            if (doTheAction) {
                // Do the action you want to perform when certain files change
            }
        },
    }
}

Usage (in rollup.config.js):

    plugins: [
        demoWatcherPlugin(['src/foo/**/*.js']),
Related