Preprocessor Defines in Typescript
Flags like #if DEBUG
are not available in TypeScript because the compilation output is always the same. In C# when you compile to debug mode the DLL
files include some extra information for debugging. In release mode that information is omitted and the DLL
files are lighter.
If you are using an automated build environment like Gulp or Grunt you can store your settings under a folder like /config/debug/config.ts
and /config/release/config.ts
then you can create two tasks:
One for debug:
$ gulp bundle-debug
And one for release
$ gulp bundle-release
To copy one file or another.
If you want to achieve something similar to #if
directives from C#, then you will have to make something that strips certain code when your application is built.
To do that, there are a few build plugins you can use. There are some build plugins (see here and here) that will strip code that is within comments like this at build time:
/* test-code */
removeMeInProduction();
/* end-test-code */
However, by using these plugins you could make a mistake in your spelling of test-code
or end-test-code
causing you to leave test code in production. You won't get a compile error about it.
Because of this, it's probably better to find a build plugin that strips a function based on its name (see here—unfortunately I can't find a gulp plugin for this). That way you could write something like this:
function ifNotProduction(func: () => void) {
func();
}
Then use it:
ifNotProduction(() => {
console.log("Only run when test.");
});
And then tell the build script to strip out the use of that function when it's not a production build.
Overall though, your simple solution of just checking a boolean is good enough.
There is code that adds support for preprocessor directive into TypeScript : https://github.com/Microsoft/TypeScript/issues/4691
However it is under discussion if it will become a part of TypeScript proper. Till then the workaround are mostly to use external build tools, or different configuration options (which strip code at compile time) and magic variables (which just disable code paths at runtime)
I always thought it was neat to use the C Preprocessor for the #ifdef
conditional in JavaScript programs. Haven’t tried it with TypeScript yet though. Here’s a nice page about it: http://www.nongnu.org/espresso/js-cpp.html.
The command shared in the link is:
# configure your web server to pipe Javascript through GNU cpp:
/usr/bin/cpp -P -undef -Wundef -std=c99 -nostdinc -Wtrigraphs -fdollars-in-identifiers -C