How to remove comments when building TypeScript into JavaScripts using rollup

Viewed 2915

I am using rollup to build my TypeScript sources. I want to remove comments ONLY, without any minification, in order to hot update code when debugging.

I have tried rollup-plugin-terser, it can remove comments but it will also minify my code somehow, I cannot completely disable the minification.

How can I do that? Thanks!

2 Answers

You should be able to achieve this too with just rollup-plugin-terser. It bases on terser so more information it's actually available on its README, here is the part related to minification. So in your case this part of rollup.config.js should looks like:

plugins: [
  terser({
// remove all comments
    format: {
      comments: false
    },
// prevent any compression
    compress: false
  }),
],

Keep in mind, that you can also enable part of configuration for production only. So having declared production const in your rollup.config.js you can do like that:

import { terser } from 'rollup-plugin-terser';

const production = !process.env.ROLLUP_WATCH;

export default {
  plugins: [
    production && terser({
      // terser plugin config here
    }),
  ],
};

Like @jujubes answered in the comments, the rollup-plugin-cleanup will do the task. I want to expand a bit.

Three things:

  • Add ts to extensions list, like extensions: ["js", "ts"] — otherwise sources won't be processed, even if transpiling step typescript() is before it — I originally came here investigating why rollup-plugin-cleanup won't work on TS files and it was just ts extension missing ‍♂️
  • code coverage is important; on default settings, this plugin would remove istanbul statements like /* istanbul ignore else */ so it's good to exclude them, comments: "istanbul",
  • removing console.log is a separate challenge which is done with @rollup/plugin-strip and it goes in tandem to rollup-plugin-cleanup. In my case, depending is it a "dev" or "prod" Rollup build (controlled by a CLI flag --dev, as in rollup -c --dev), I remove console.log on prod builds only. But comments are removed on both dev and prod builds.

currently, I use:

import cleanup from "rollup-plugin-cleanup";
...
{
  input: "src/main.ts",
  output: ...,
  external: ...,
  plugins: [
    ...
    cleanup({ comments: "istanbul", extensions: ["js", "ts"] }),
    ...

Here's an example of rollup-plugin-cleanup being used my Rollup config, here's my Rollup config generator (in monorepos, Rollup configs are hard to maintain by hand so I generate them). If you decide to wire up --dev CLI flag, the gotcha is you have to remove the flag from the commandLineArgs before script ends, otherwise Rollup will throw, see the original tip and it in action.

Related