require.js Isn’t Too Bad after All

I remember working with require.js a while ago in conjunction with Backbone. I stumbled upon it in some tutorial that used it, so I used it as well, not really knowing why.

What I remember is, that the experience was pretty unpleasant, mainly because I spent a lot of time looking for forks of the libraries I wanted to use and then spending even more time when new versions were available. (I also remember a lot of strange errors…)

One year passed.

Turns out require has addressed this issue since then with something called shim (why is it called like that?). It allows you to turn any JS library into a require module, like this:

require.config
  paths:
    jquery: 'lib/jquery-2.0.2'
    underscore: 'lib/underscore-1.4.4'
    backbone: 'lib/backbone-1.0.0'

  shim:
    underscore:
      exports: "_"
    backbone:
      deps: ["underscore", "jquery"]
      exports: "Backbone"

That was so easy, I didn’t even believe it would work (but it did). After that I was able to use my libraries just as I was used to with the forked versions:

require [
  'jquery'
  'backbone'
  'models/clockmodel'
  'views/clockview'
], ($, Backbone, ClockModel, ClockView) ->

Pretty neat!


© 2022 Florian Klampfer

Powered by Hydejack v9.1.6