Search code examples
rollup

Watch package.json, add version to the bundle


I'm bundling a library with rollup and trying to add a version from package.json into the code itself.

Relevant bits of rollup config:

import pkg from './package.json'

output: [{
  footer: `foo.version = '${pkg.version}'`
}]

The problem is, it's not getting updated with hotreload/watch. (rollup -w -c rollup.development.config.js')

Tried a few things:

  • using output plugins: they don't run again on watch
  • doing a dynamic import in the footer: not running again either
  • custom watcher plugin to include package.json: this triggers reload, but still not running the code that would read the updated value (plugins or footer)

Is there a way to do this? I wouldn't mind doing a full rebuild when package.json changes, but I'd like to avoid restarting the process manually. I'm frankly confused how such a simple thing can be this complicated. Thanks

EDIT: The version is not updated even when I do this:

const getVersion = () => ({
  async renderStart () {
    const data = await import('./package.json')
    console.log('version: ' + data.version)
  }
})

export default async () => ({
  output: [{
    plugins: [getVersion()]
  }]
})

Thought it's a cache, so I tried invalidating it with ?date=' + Date.now(), but that just gives me Error: Cannot find module './package.json?test=1652969298057'. Seems like rollup is using require :(


Solution

  • Figured it out:

    rollup.config.js

    import glob from 'glob'
    import path from 'path'
    import fs from 'fs'
    
    const watcher = (globs) => ({
      buildStart () {
        for (const item of globs) {
          glob.sync(path.resolve(item)).forEach((filename) => { this.addWatchFile(filename) })
        }
      }
    })
    
    const updateVersion = () => ({
      renderStart (outputOptions, inputOptions) {
        outputOptions.footer = () => `library.version = ' + ${JSON.parse(fs.readFileSync('package.json', 'utf8')).version}'`
      }
    })
    
    export default {
      plugins: [
        watcher(['package.json'])
      ],
      output: [{
        plugins: [
          updateVersion()
        ]
      }]
    }