Search code examples
optimizationnode.jsrequirejsjs-amd

jQuery as AMD module and optimizing with r.js


Allright, he is the thing. I am using curl.js for my AMD loader, but i don't like much of "cram" because it needs to be run on unix and i am developing on Windows. So the r.js adapter for nodeJS from RequireJS library comes in mind, because node has already binary for Windows.

Now jQuery in current version (1.6.4) is not valid AMD module (coming in version 1.7) and there is dependencies in jQueryUI components, so i had to fake like this:

curl( [js!Core/jquery.js] )
    .then( function() {
        define('jquery', function() { return jQuery; });
    })

My application is happy with this. However using r.js (version 0.26.0) fails on this part with following error:

Tracing dependencies for: boot
function (){return jQuery}

node.js:207
    throw e; // process.nextTick error, or 'error' event on first tick
          ^
ReferenceError: jQuery is not defined
at eval at <anonymous> (r.js:7468:30)
at main (r.js:770:33)
at callDefMain (r.js:840:18)

This is my app.build.js

({
    appDir: '../',
    baseUrl: 'Scripts/',
    paths: {
        'link': '../../../Lib/@Javascript Libs/curl.js/src/curl/plugin/link.js'
    },
    dir: 'built',
    optimize: 'none',
    modules: [
        { name: 'boot' }
    ]
})

And here is complete boot.js for reference (coffeescript):

require([
    'link!styles/main.css'
    'js!Core/jquery.js!order'
    'js!Core/underscore.js!order'
    'js!Core/backbone.js!order'
]).then ->
    define 'jquery', -> jQuery

.next(['Router/MainRouter'])
.then (MainRouter) ->
    new MainRouter()
    Backbone.history.navigate('home') unless Backbone.history.start(
        pushState: false
    )

Thank you in advance for any hint where the catch can be...


Solution

  • Correct. RequireJS uses a different syntax on its global requirejs() (aka require()) function. RequireJs also doesn't have the "js!" plugin built-in. You may have to include a path to it in your config. You could also use RequireJS's syntax for non-module javascript files.

    Also: cram 0.2 will support Windows environments using Rhino. We're writing tests for cram 0.2 and will be releasing it shortly.

    RequireJS syntax (remove js! prefix and include .js extension):

    require([
        'link!styles/main.css'
        'order!Core/jquery.js'
        'order!Core/underscore.js'
        'order!Core/backbone.js'
    ], function (maincss, jQuery, underscore, backbone) {
        // do something here
    });