How do I make my JavaScript project more manageable?

I am currently building a JS library that can connect to and interact with any HTML5 Canvas element context.

However, the project is starting to grow with more files and thousands of lines of code. Each file represents a different object / module. Every file is currently laid out this way, and I really would like to keep some semblance of this style:

Object = function() { 
    // constructor
}

Object.prototype.method1 = function() {
    // Logic
}

Object.prototype.method2 = function() {}; // .... etc

      

And in the HTML development version, I have bajillion script tags (one for each file) that need to be in exact order (for dependencies). I understand that this is very inefficient and not very convenient. But I'm not sure what is the best fit to try and make my project easier to build and maintain. Port to NodeJS for the convenience of CommonJS tools and modular system? Convert to RequireJS? I'm just starting to read about Grant, is this helpful for my situation?

Improving my organization and implementing some kind of build system is something I've put off for a while. And I regret it now.

+3


source to share


2 answers


You need a system of modules .

RequireJS, with the RequireJS optimizer, is the canonical solution here. You can use browserify if you're more of Node.js-leaning, or use the cjsTranslate function of the RequireJS optimizer if you don't like AMD's cruft ( define(function (require, exports, module) { ... });

) --- perhaps in conjunction with Cajon in development.




A build tool like Grunt is not the most important factor here. This is useful mainly when you have multiple build steps - for example, run the RequireJS optimizer and then compile your SASS for raw CSS, then merge the CSS, then turn your images into sprites, then ... etc.

+2


source


It's important to note that for each of these tags, the <script>

browser has to make another HTTP request - even if it's loaded from the cache, the browser has to ask the server if the file has changed.

I would suggest writing a small program like this PHP script to combine all your .js files into one:

<?php
function loop($dir="./") {
    $ret = Array();
    foreach(glob($dir."*",GLOB_ONLYDIR) as $d) $ret = array_merge($ret,loop($d));
    foreach(glob($dir."*.js") as $f) $ret[] = $f;
    return $ret;
}
$out = fopen("__main.js","w");
foreach(loop() as $file) {
    if( $file == "./__main.js") continue; // don't include "main" script
    fwrite($out,file_get_contents($file));
}
fclose($out);
?>

      



Now you can only have one tag <script>

pointing to this file __main.js

and all your scripts will be there.

If your scripts need to be in a specific order, then you are doing something wrong. If you only define objects in these files, it shouldn't depend on others, as references should be in methods (for example, consider a method init

).

0


source







All Articles