hashrollupjs

Hashed file names using Rollup


I am fairly new to bundlers and rollup specifically. What is the best way to conditionally hash file names in rollup.config.js when building for production, while at the same time saving the index.html to reference the new .css and .js hashed versions?

I see this in the docs, but I guess I don't know how to conditionally set these options based on dev/prod settings?

output: {
        sourcemap: true,
        format: 'iife',
        name: 'app',
        file: 'public/build/bundle.js'
       // entryFileNames : 'bundle[hash].js
    },

or is using rollup-plugin-hash a better solution? still not sure what the best practice would be for updating the index.html (and what does the manifest file option provide?)


Solution

  • You can use a plugin like @rollup/plugin-html to generate a html file that references the hashed filenames.

    It is also possible to use the rollup-plugin-manifest to generate a JSON file that will contain these hashed filenames.
    This is useful when you can't generate the HTML using rollup for some reason.

    Since the Rollup config file is just Javascript, you can include some if statements that return different results based on the dev/prod settings.

    const isProduction = process.env.NODE_ENV === 'production';
    
    export default {
      output: {
        sourcemap: true,
        format: 'iife',
        name: 'app',
        entryFileNames: isProduction ? 'bundle[hash].js' : 'public/build/bundle.js',
        dir: './',
      }
    };
    

    see output.entryFileNames