Sathya
Sathya

Reputation: 5308

RequireJS - why should i shim libs like jquery, backbone etc

I saw lot posts and articles in this area. Some of them are,
Developing Modular Backbonejs Applications
TodoMVC with requireJS
Stack Overflow post with most upvotes

So no problem for me to modularize jquery, backbonejs and other libraries. My questions is why should i do it? Because on each js file we are going to use jquery and backbonejs and adding this below code on each file seems extra burden to me.

define([
    'jquery',
    'underscore',
    'backbone',
    'myFile1', 'myFile1'
], function ($, _, Backbone, module1, module2) {

Why should i not include them directly into html file before including requireJS like below?

<script src="../lib/client/jquery.js"></script>
<script src="../lib/client/underscore.js"></script>
<script src="../lib/client/backbone.js"></script>
<script data-main="client/main" src="../lib/client/require.js"></script>

In this case, i don't need to define jquery or backbonejs on every js file. I can modularize my own js files alone, like below.

define([
    'myFile1', 'myFile1'
], function (module1, module2) {

What are the disadvantage by this method? Is this right approach? Did i break any requirejs rules?

Upvotes: 3

Views: 219

Answers (1)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276306

We shim because modules like jQuery and Backbone do not work in the RequireJS model .There is no define( statement defining them so they must be shimmed to work like and with real Require modules directly.

Yes, what you said (just dumping them in the global namespace) works, you're not breaking any 'rules'. When you add a script tag all it does is dump the code in the global namespace - so all your modules will, in fact have access to Backbone and jQuery in the above example.

However it has three disadvantages:

  • One of the thing we gain with Require is that our dependencies are explicit , every time a module needs something we know that - so our dependency management is a lot clearer (We know what modules depend on jQuery and what don't for example - so we know which are safe to use in a new project without jQuery).

  • Another thing is that we stay consistent across our code, we keep declaring every dependency exactly the same way and using it in exactly the same way. RequireJS shims let us keep acting like that's what's done with libraries like jQuery or Backbone.

  • Because of the implicit dependencies, if you ever want to reuse your code - including jQuery after your RequireJS modules will be a run time error which is not always trivial to understand, unlike Require which would tell you that it can't load the module jQuery (and not something like $ is not defined, or even worse "[Object object] is not a function" or something like that.

Upvotes: 5

Related Questions