Search code examples
rollup

What is the correct way in Rollup.js to add a banner to minified files?


What is the correct way to add a banner to a minified js file created with Rollup.js?

So far I have tried the builtin output.banner option, but this gets removed by the minifier.

// rollup.config.js
export default {
  ...,
  output: {
    ...,
    banner: BANNER,
    sourcemap: true,
  },
  plugins: {
    terser(),
  }
}

I have also tried using rollup-plugin-banner.

{
  ...,
  output: [{ 
    ...,
    sourcemap: true,
  }],
  plugins: [
    terser(),
    banner(BANNER),
  ],
}, 

This kind of works, but throws the following error message for each file processed by rollup.

(!) Broken sourcemap
https://rollupjs.org/troubleshooting/#warning-sourcemap-is-likely-to-be-incorrect
Plugins that transform code (such as "banner") should generate accompanying sourcemaps.

How do I get this to work without the error messages?


Solution

  • It's actually because of terser:

    comments (default "some") -- by default it keeps JSDoc-style comments that contain "@license", "@copyright", "@preserve" or start with !, pass true or "all" to preserve all comments, false to omit comments in the output, a regular expression string (e.g. /^!/) or a function.

    You can either change your banner text a bit (based on the above rules) so terser won't remove it or use terser's preamble option (instead of rollup's output.banner):

    plugins: [
        // ...
        terser({
            format: {
                preamble: '// Copyright example ...'
            }
        })
        // ...
    ]