Over a million developers have joined DZone.

Importing External Files in JavaScript

DZone's Guide to

Importing External Files in JavaScript

· Web Dev Zone
Free Resource

Discover how to focus on operators for Reactive Programming and how they are essential to react to data in your application.  Brought to you in partnership with Wakanda

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:


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


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

Learn how divergent branches can appear in your repository and how to better understand why they are called “branches".  Brought to you in partnership with Wakanda


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!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}