This text is superseded by https://gist.github.com/djedr/7d21eac05ce2bbbca29b29d532a1fbe4.
There are some reasons listed here. To expand on that, using the C preprocessor with JavaScript project also gives us an easy way to share constants between different files. Back-end (Node.js) and front-end (Angular, React). But you can also share constants between .js files and .css files or any other text formats. No fuss. Just #include "constants.cpp"
.
Macros that operate on plain text are more limited and sloppier than macros that operate on syntax trees, like sweet.js. But they are also simpler. And very often enough.
Also:
- cpp is simple
- anybody who wrote C, C++ or Objective-C used it and knows the basics
- it's widely available
- it's stable
Assuming you have the C preprocessor available from the command line under the cpp
command, in order to invoke it in a JavaScript-friendly way, use it like so:
cpp input.cpp.js -P -nostdinc -o output.js
where:
-
input.cpp.js
is the name of the to-be-preprocessed input file, -
-P
tells the preprocessor (quoting the manpage):Inhibit generation of linemarkers in the output from the preprocessor. This might be useful when running the preprocessor on something that is not C code, and will be sent to a program which might be confused by the linemarkers.
-
-nostdinc
tells the preprocessor (quoting the man page):Do not search the standard system directories for header files. Only the directories you have specified with -I options (and the directory of the current file, if appropriate) are searched.
-
-o output.js
specifies that the preprocessor's output will be written to a file namedoutput.js
See the above link again to see more options you might want to pass to the command and cpp's man page for explaination of these.
http://www.nongnu.org/espresso/js-cpp.html
https://rreverser.com/es6-modules-are-dead-long-live-c-preprocessor/
http://www.julienlecomte.net/blog/2007/09/16/