grunt-prepr
Grunt task that provides a C/C++ like preprocessor (with some limitations, see examples) for JavaScript, CSS and other source code. Supported directives are:
#ifdef
#ifndef
#endif
#define
#undef
The task allows to perform both conditional preprocessing of the source code and to define macros.
Getting Started
Setup task grunt-prepr with grunt.js
Install this task next to your project's grunt.js
gruntfile with:
npm install grunt-prepr
Then add the line bellow to your project's grunt.js
gruntfile:
grunt;
How to config
The standard Grunt conventions are followed when configuring task:
grunt;
Using as browserify transform
browserify: options: transform:
Examples
For more details, refer to the examples in the repository and Jasmine specs.
Although the examples below deal only with JavaScript and CSS, the preprocessor can be used for any source files.
Conditionals
Input:
{//#ifdef DEBUG console;//#endif return x + y;}
Task configuration:
grunt;
Result of running grunt prepr:prod
:
{ return x + y;}
Result of running grunt prepr:dev
:
{ console; return x + y;}
So in the development version logging to console will be left intact while in the production version it will be removed.
Defining macros
With macros we can, for example, define colors in CSS.
Input:
/* #define $COLOR1 rgb(12, 12, 12) #define $COLOR2 rgb(23, 45, 67) #define $DEFAULT_BOX_WIDTH 300px*/
Output:
Macros can also take parameters, please, refer to the Jasmine specs.
Avoid abusing macros
A word of caution about using macros. The same concerns as in C/C++ apply, the preprocessor is pretty unaware of the structure of the code (unlike Lisp macros). It treats code as strings and modifications then are pretty limited, the source code with preprocessor directives may become invalid if not handled by a preprocessor and moreover the resulting code may also be invalid if the macros were defined incorrectly.
I would say that #define
should not be used with JavaScript in most of the cases because of these limitations. Just use the normal functions instead. For example,
instead of:
#define X > Y ? X : Y ;
use pure JavaScript solution:
{ return x > y ? x : y;} ;
License
MIT License (c) Anton Ivanov
Credits
The following plugins are used during the build:
- JSHint for Grunt grunt-contrib-jshint
- Jasmine for Grunt grunt-contrib-jasmine
The task was inspired by:
- C preprocessor c-preprocessor