A simple way to work with several files in JavaScript
Working with JavaScript can be a mess if you don't split your code in several files.
Suppose you have a products catalog, maybe your JavaScript application can be divided in this modules:
- Application init
- Product list
- Product card
And your code, a single file named "catalogApp.js" with something like this:
var App = function(options) {
...
return this;
};
App.prototype = {
init: function() {
...
}
};
var ProductList = function ...
var ProductCard = function ...
The problem here is organization. All the codebase in one single file is not a good idea, for many reasons.
GNU make
A simple way to solve this problem, is using the GNU make utility, available commonly on Unix sytems like Linux or Mac OS X (require Xcode and Command Line Tools) and Windows using GnuWin32.
You can divide the catalog app in three files, one per module, this way:
- app.js - Application init
- product_list.js - Product list
- product_card.js - Product card
And concatenate them in a single file, using the "cat" command ("type" in Windows):
cat app.js\
product_list.js\
product_card.js\
> catalogApp.js
The "make" command needs a configuration file (Makefile):
PACKAGE=catalogApp
RELEASE_DIR=../
RELEASE_FILE= $(PACKAGE).js
all:
@@echo "Building..."
@@cat app.js\
product_list.js\
product_card.js\
> $(RELEASE_DIR)/$(RELEASE_FILE)
@@echo "Build completed."
Now you can go to the project's source code folder and type "make" in order to compile your code in a single file. You can add other lines to the "Makefile" too, for example to check or minify your code.
Written by emi420
Related protips
Have a fresh tip? Share with Coderwall community!
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside