I'm building my first (non-spaghetti) large JavaScript application. While the introduction of RequireJS and other dependency management frameworks for JavaScript makes it easier to split up files, I'm unclear as to how push a large code base to production. What I would like is a way to aggregate and minify/uglify my JavaScripts for production, using something like Ready.js and UglifyJS. Or some other approach, if it makes sense.
How do developers with large JavaScript apps in production handle their structure in development and in production?
I could, for example, use RequireJS in development and then use Ready/Uglify to aggregate/minify. But then my code would have pointless require()'s
scattered throughout. I'm sure there's a better approach.
I'm also confused about including jQuery within these files. Should I be wrapping each and every separate jQuery file (for example Backbone views that use jQuery) within their own separate $(document).ready(function(){...})
? That seems very un-DRY.
You can use the RequireJS optimizer. The requires are not pointless, even in the compressed application, because you always have to get a reference to the module. The optimizer docs also say, that it will not include a module that has been loaded with a variable like
var mods = someCondition ? ['a', 'b'], ['c', 'd'];
require(mods);
I think that RequireJS should wait till the DOM is ready and all modules have been loaded, so you don't need to wrap every file.
That said, my favourite package manager is still StealJS. It can kick out unnecessary calls in a production build and a module is always encapsulated in a closure that gets the jQuery object passed and waits till the DOM is ready and all scripts have been loaded. Unfortunately it is not yet compatible with the CommonJS module specifications.
I've found YUI Builder works well for me. I'm not sure how useful it is if you're not using YUI 3, but there's a good chance you could adapt it to your needs.
On the other hand, have you taken a look at RequireJS Optimizer?
Regarding document.ready
handling; I think it's good practice to not let code in modules do anything until they're initialized or called. So I would have a single $(document).ready()
in a <script>
tag at the bottom of the page itself, which "glues together" the modules that are needed on that page.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With