问题
Is there anything in JavaScript or Visual Studio to detect if the code is used in debug-mode? Something like "#if DEBUG" in C#, but for JavaScript?
回答1:
No.
#if
/#endif
are preprocessor directives in C# (and other languages) that tells the compiler to conditionally include/exclude a section of code when compiling.
JavaScript is a script language that is not precompiled, and therefore it would not make much sense to have preprocessor directives like these.
回答2:
A bit late, but I needed the same and could not give up until a viable solution.
I have a kind of "main" javascript file, where I have a line like:
Site.DEBUG = false;
Then in the code I can check for this constant. Now I needed to solve that at build time, some automation would set this for me according to project configuration. Here I've found fnr.exe command-line tool for find and replace in files. It's a quite good piece of utility, would be worth to check out anyway. So at this point I've created a folder in the project directory called BuildScripts
, I've copied the fnr.exe
file into it, and created a batch file like this.
switch_client_debug.bat
REM Params: path to folder, filename, change-DEBUG-from-this, to-this
fnr.exe --cl --dir "%1" --fileMask "%2" --caseSensitive --showEncoding --find "DEBUG = %3" --replace "DEBUG = %4"
Then I defined the corresponding pre-build events at the web project like this:
cd $(ProjectDir)BuildScripts
call switch_client_debug.bat $(ProjectDir)ts site.ts false true
and its pair at Release config:
cd $(ProjectDir)BuildScripts
call switch_client_debug.bat $(ProjectDir)ts site.ts true false
Now everything works like a charm and I can have logging, tracing, special logic for Debug and for Release configuration in Javascript.
回答3:
Only for IE there is the conditional compilation:
/*@cc_on
@set @version = @_jscript_version
@if (@_win32)
document.write("You are running 32 bit IE " + @version);
@elif (@win_16)
document.write("You are running 16 bit IE " + @version);
@else @*/
document.write("You are running another browser or an old IE.");
/*@end @*/
nice article here
来源:https://stackoverflow.com/questions/22343819/if-debug-in-javascript