1
votes

I have been working on a Backbone/RequireJS app for sometime, and am now updating it to use Marionette. It breaks at first as Marionette AMD tries to search for jquery, backbone and underscore in root /, however, I have these libraries in /lib, I could modify the code. Whats the proper way of fixing this? (if possible not moving libraries out of /lib).

What I did now is use the non AMD version which works. But sometimes, I get CollectionView of undefined errors in some views, which makes me wonder if its related to using non-AMD build for RequireJS

2

2 Answers

2
votes

You can't (or at least, shouldn't) modify the source code of every one of your libraries to tell it where its dependencies are. You can, however, control where your code is.

The approach I use, which I copied from Volo's default project template, is to set RequireJS's baseUrl to the /lib folder so your library code will find its dependencies easily, and then use the paths config to alias 'app' to wherever my code lives, like so:

Directory layout

/www 
  /js
    main.js
    /lib
      backbone.js
      backbone.marionette.js
      (etc)
    /app
      my-code.js
      view.js

main.js (or wherever you're configuring RequireJS)

requirejs.config({
    baseUrl: 'www/js/lib',
    paths: {
        app: '../app'
    }
});
// Go on to load another module that contains the actual app. Example:
requirejs(['app/my-code']);

All paths in your paths config are relative to the baseUrl. Defining a mapping for app like above means that when RequireJS loads a module named app/foo, it will use (baseUrl)/../app/foo.js:

my-code.js

define(['backbone', 'app/view'], (Backbone, MyView) {/*...*/}
2
votes

This is a common problem and there are two solutions that I know of:

1) modify the AMD version of Marionette for your project.

Specify the correct path to these two libraries, and you'll be good to go. This is a simple change in the dependency list of Marionette and won't affect the rest of the functionality.

But this is a bad idea. It means you have to change the code, and any time you get a new version you have to change it again.

2) use a named module/path in requirejs

I've specified the dependencies as "jquery", "underscore", "backbone" strings, which means you can use a named path to configure where these dependencies live.

Include this in your requirejs configuration:


require.config({
  paths: {
    "jquery": "/your/path-to/jquery"
  }
});

and now the "jquery" dependency will be found by Marionette

This is the better of the two solutions as it does not require you to change the marionette file. It only requires you to configure RequireJS to provide these named paths.