Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove comments when building TypeScript into JavaScripts using rollup

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!

like image 417
Summer Sun Avatar asked Apr 17 '26 17:04

Summer Sun


1 Answers

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.

like image 79
revelt Avatar answered Apr 20 '26 06:04

revelt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!