Importing External Files in JavaScript

JavaScript

As JavaScript application grows, navigation on the code becomes a hell. It comes on mind how useful would be to have ability including JavaScript files. For example, thanks to include/require statements we can build an expressive file structure in PHP. Let’s say following PSR-0 standard we have one class per file (or one prototype object per file in JavaScript) and class name (namespace) reflects the location of the file where it belongs. Well, on server side (e.g. with NodeJS) that is achievable with CommonJS. Of course you have to export every object of a single file as a module, which is often not a module in fact. As for the client side, modular JavaScript implies that all the dependent modules load asynchronously and separately. If every object makes a module to load that sounds nothing like a good idea.

In the other hand you can simply combine multiple JavaScript files into one (e.g. with compressJS.sh). You can use Apache ANT for concatenation or you can exploit Grunt as JQuery project. But none of those really help to organize files into a decent structure such as I was mentioned above. So I was thinking of a compiler which could produce a combined JavaScript file from one containing include directives, quite the same as CSS preprocessors (LESS/SASS/Compass) and RequireJS Optimizer treat @import CSS at-rule. As I didn’t find anything like that in Internet, I made a dead simple script which looks in a given JavaScript file for $import("./path") function calls and inline content of the referenced files recursively.

Let’s say we have files:

src/main.js

var foo = $import("./Form/Input/Tel");

src/Form/Input/Tel.js

function() {
    return {
          prop: "",
          method: function(){}
    }
}

We can run compiler:

node jsic.js src/main.js build/mail.js

And get the combined file

build/main.js

var foo = function() {
    return {
          prop: "",
          method: function(){}
    }
};

Fork me on Github https://github.com/dsheiko/jsic