ES6 modules are dead, long live C preprocessor!

Posted on:

Did you know you could use C preprocessor even for JavaScript files? (yes, it doesn't care about syntax that much)

Say, we want to implement C-like "modules" (inclusions) in JavaScript.

Create first file 1.js (filenames don't matter) like this:

#ifndef HELLO_1
#define HELLO_1

console.log("hello");

#endif

(#ifndef/#define is standard C practice for avoiding double-inclusion)

Then, create 2.js:

#ifndef HELLO_2
#define HELLO_2

#include "1.js"
console.log("world");

#endif

And now you can bundle them into one file with:

cpp -P -Wundef -nostdinc -C 2.js

(here we ask cpp just to preprocess our file with basic warning and preserving comments; also we ask not to search standard C library for includes)

And as a result you would get:

console.log("hello");
console.log("world");

Note that you can even define and use full-featured macroses inside of your JavaScript - just #define them and ready to go!

P.S. Yes this is a crazy hack (as most of other stuff in my blog), and there are more appropriate tools for transforming JavaScript, but why not to try if we can? :)

UPD [17.08.2015]: Turns out it's not as crazy experiment as I initially thought. Ryan Grove on Twitter just mentioned that they actually used this technique at Yahoo Search in 2007:

@RReverser Believe it or not, we used this technique in our production JS workflow at Y! Search ~2007. Worked well. http://t.co/HGSFfU1W1u > — Ryan Grove (@yaypie) August 16, 2015


More posts: