macro definition in javascript

后端 未结 6 684
一向
一向 2021-01-01 22:07

Is there a way that I can define a macro similar to C/C++ macros in Javascript?

I want to use this for debug statements: Something like

#ifdef TEST         


        
相关标签:
6条回答
  • 2021-01-01 22:56

    While is true that there is no compile time as @sapht said, you can pre-process your files if you want. Typically I use an ant script to combine many Javascript files together and add build information.

    From a google search I see there is a Javascript preprocessor that you may find interesting: http://www.bramstein.com/projects/preprocess/

    0 讨论(0)
  • 2021-01-01 22:57
    var de = false; // true when debugging
    function bug( msg ){ ... display msg ... }
    

    Usage:

    de&&bug( "hello world")
    

    When "de" is false (production mode), the overhead is minimal.

    0 讨论(0)
  • 2021-01-01 23:02

    With Builder – https://github.com/electricimp/Builder, you can do like:

    @macro MYDEBUG(x)
      debug(@{__FILE__}, @{x});
    @end
    
    ...
    
    @{MYDEBUG(100500)}
    

    Also supports for includes directly from GitHub.

    0 讨论(0)
  • 2021-01-01 23:06

    For those who are still interested:

    https://github.com/dcodeIO/Preprocessor.js

    A JavaScript source file preprocessor in pure JavaScript, e.g. to build different versions of a library.

    Examples:

    // #ifdef FULL
    console.log("Including extension");
    // #include "path/to/extension.js"
    // #else
    console.log("Not including extension");
    // #endif
    
    // #if 1==2
    console.log("1==2");
    // #elif 2==2
    console.log("2==2");
    // #endif
    
    0 讨论(0)
  • 2021-01-01 23:10

    Javascript has no macros since there is no compiler. You could use console.log and write a regex to strip those statements when deploying.

    0 讨论(0)
  • 2021-01-01 23:11

    There isn't a way to do this in JavaScript. You could have a global variable like

    var isDebugging = false;
    

    Then when writing code, just check if the variable is true. Obviously this will create some unwanted overhead with file size, and a very slight performance loss. But other than specifying your own format, and running the code though a tool to strip debugging code out before you upload.

    Something like

    var foo = function() {
       <!-- document.write( "blah" ); -->
    };
    

    For a release build, you would remove everything inside the tags, inclusive. And for a debug build you could just remove the tags, but keep the code. Something like this could be performed with an Ant build script or similar.

    0 讨论(0)
提交回复
热议问题