Over a million developers have joined DZone.

Importing External Files in JavaScript

· Web Dev Zone


As a JavaScript application grows, navigation on the code becomes hellish. It comes to mind how useful it would be to have the ability to include JavaScript files. For example, thanks to include/require statements we can build an expressive file structure in PHP. Let’s say following PSR-0 standards we have one class per file (or one prototype object per file in JavaScript) and the class name (namespace) reflects the location of the file where it belongs. Well, on the 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 at all. 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.

On 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:




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

We can run compiler:

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

And get the combined file


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

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



Published at DZone with permission of Dmitry Sheiko, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}