Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hashed file names using Rollup

Tags:

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?)

like image 699
user1475540 Avatar asked Feb 07 '20 14:02

user1475540


People also ask

What is Rollupjs?

Rollup is a module bundler for JavaScript which compiles small pieces of code into something larger and more complex, such as a library or application. It uses the new standardized format for code modules included in the ES6 revision of JavaScript, instead of previous idiosyncratic solutions such as CommonJS and AMD.

Does rollup use Webpack?

While Webpack is focused on using CommonJS as its primary module system and converting everything to that, Rollup decided to take the opposite approach — focusing on ES Modules instead. One of the core differences between CommonJS and ES Modules, is that CJS is a dynamic module system.


1 Answers

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',
    entryFileName: isProduction ? 'bundle[hash].js' : 'public/build/bundle.js',
    dir: './',
  }
};
like image 159
NotWoods Avatar answered Oct 05 '22 23:10

NotWoods