2013-01-09 53 views
4

這是我的情況,使用帶有Requirejs的Backbone和Handlebars。Requirejs,杏仁,骨幹,把手

我下面CommonJS的模塊定義風格,因爲我發現自己更舒服:

define(function(require) { 
    var Backbone = require('Backbone') 
    var Item = require('model/item') 
    // ... 
}) 

這是我requirejs配置:

require.config({ 
    baseUrl: "/javascripts/", 
    paths: { 
    jquery: 'components/jquery/jquery', 
    underscore: 'components/underscore/underscore', 
    backbone: 'components/backbone/backbone', 
    handlebars: 'components/handlebars/handlebars', 
    text: 'components/text/text' 
    }, 
    shim: { 
    underscore: { 
     exports: "_" 
    }, 
    handlebars : { 
     exports: "Handlebars" 
    }, 
    backbone: { 
     deps: ['underscore', 'jquery'], 
     exports: 'Backbone' 
    } 
    } 
}); 

一切之前運行平穩優化,沒有問題發生。

但是,經過r.js依賴關係的優化似乎打破了。 我想在生產中使用杏仁JS,所以這裏是我的生成文件:

({ 
    baseUrl: ".", 

    paths: { 
     jquery: "components/jquery/jquery", 
     underscore: "components/underscore/underscore", 
     handlebars: "components/handlebars/handlebars", 
     backbone: "components/backbone/backbone", 
     text: "components/text/text" 
    }, 

    // we use almond minimal amd module loader 
    name: "components/almond/almond", 

    // the application entry point 
    include: ['app/init'], 

    // we need to teel almond to require app/init 
    insertRequire: ['app/init'], 

    out: "main.js", 

    cjsTranslate: true, 

    wrap: true, 

    optimize: "none" 
}) 

現在,當我運行在瀏覽器優化的JavaScript,我得到的是錯誤信息,說我jQuery和車把未定義(當然,都不是Backbone.$)。

簡單的解決方法是迫使jQuery的負載,並將其分配給骨幹,像這樣:

var $ = require('jQuery') 
var Backbone = require('Backbone') 
Backbone.$ = $ 

但聽起來很愚蠢的,多餘的我。 我覺得我做錯了什麼,但無法弄清楚什麼。

優化後的車把也無法加載爲依賴關係。 如果我強制加載(就像我使用jQuery一樣),在構建過程中我收到一條錯誤消息,說我找不到模塊fs(一個npm包)。

我使用Google搜索,但只在Google羣組(https://groups.google.com/forum/?fromgroups=#!topic/requirejs/lYwXS-3qjXg)上發現了與我的問題有關的主題,即使提議的解決方案根本無法工作。

+0

您可以在這裏閱讀關於在backbone中使用require.js的簡單教程:http://addyosmani.github.com/backbone-fundamentals/#modular-development –

+0

感謝您的幫助。我已經看了Addy的教程,但在我看來,我做錯了什麼。我正在更深入地研究它。 –

回答

3

我想你應該在你的構建文件中添加Shim的配置。

+0

儘管使用導出,但確保Backbone被導出或使用BB的庫創建者AMD實現。 – adrian

+2

最長問題獎的最短答案將發給你。 – dezman