Search code examples
build-processcoffeescriptconditional-compilationuglifyjs

Conditional compilation in CoffeeScript/UglifyJS


Using Coffeescript I need to have a go through a build script anyway to update my .js files, and I have two of them, one for debugging and one for production (one uses Uglify to minimize the files, one does not). So I was thinking that it would be convenient to have some conditional compilation as well, with code that only enters the debug build.

What is the easiest way to achieve this, ideally controlled by a simple command line switch that I can give to either coffee or uglify?


Solution

  • If you're writing a build script anyway, you can add a preprocessor step to it. Since CoffeeScript uses # to denote comments, the C preprocessor seems like a good choice. You can denote debug code with #ifdefs:

    some code...
    #ifdef DEBUG
    debug code...
    #endif
    

    Then, you can preprocess the debug version with cpp -E -Xpreprocessor -DDEBUG <filename> -o <outfile> and compile <outfile> with CoffeeScript. Similarly, preprocess the production version with cpp -E <filename> -o <outfile>.

    Edit: This one's tough, because it means any CoffeeScript comments that are not indented will break the preprocessing step. Not sure how much of a problem this is to you. For example,

    code...
    #comment about the code
    

    will break the build, but

    code...
      indented code...
      #indented comment
    

    will work fine, because the preprocessor doesn't look at lines unless their first character is a #.