Michael Stum
Michael Stum

Reputation: 181074

Are there TypeScript-only comments that don't get written into the .js?

If I add a regular comment (either /* */ or //) to a .ts file, it gets written to the output js file unless I specify removeComments during the compilation.

However, I wonder if it's possible to do it the other way round, keep comments except for "TypeScript-only" comments. This would be similar to how the Razor View Engine for ASP.net allows to use @* Comment *@ to indicate comments.

I know I could use copyright comments (/*!) as regular comments and javascript comments as TypeScript only comments (and this remove them with removeComments), but that seems really awkward and hard to remember.

Without the use of additional build tools/processing, does the TypeScript compiler have a way that I've overlooked, or is removeComments the only applicable choice here?

Upvotes: 8

Views: 560

Answers (1)

jcalz
jcalz

Reputation: 330086

If nobody finds an "official" way to do this, you could always put the comments in a section of code that you know will be erased from the emitted JavaScript. It's definitely a hack, but depending on your use case it could work for you:

interface TSOnlyComment {
  // this comment will definitely not appear in the JS
}

So that's a dummy empty interface named TSOnlyComment. You can reuse that interface to make multiple comments, since TypeScript will interpret that as interface merging:

interface TSOnlyComment {
  // This only appears in TS, not JS
}

const javaScriptAwesomenessFactor = 1e9; // JS rules!

interface TSOnlyComment {
  // Just kidding, TS is better than JS.
}

// let's print out how awesome JS is
console.log(javaScriptAwesomenessFactor);

interface TSOnlyComment {
  // Ha ha, we are laughing at JS behind its back.
}

That should emit JS something like (depending on your --target):

var javaScriptAwesomenessFactor = 1e9; // JS rules!
// let's print out how awesome JS is
console.log(javaScriptAwesomenessFactor);

So, maybe that works for you? Good luck!

Upvotes: 2

Related Questions