簡體   English   中英

使用requirejs加載小胡子

[英]Loading mustache using requirejs

我想通過requirejs加載和使用小胡子。

也許這個問題已經問過:
使用RequireJS使用Mustache的AMD模塊加載錯誤

無論如何,我想弄清楚如何修復我的代碼:


main.js

require.config({
    paths: {
        jquery: 'libs/jquery/jquery',
        underscore: 'libs/underscore/underscore-min',
        backbone: 'libs/backbone/backbone-optamd3-min',
        mustache: "libs/mustache/mustache"
    }
});

require([
    'views/app'
    ], function(AppView){
        var app_view = new AppView;
 });

app.js

define([
    'jquery',
    'underscore', 
    'backbone',
    "mustache"
    ], function($, _, Backbone, Mustache) {
        console.log($, _, Backbone, Mustache); // <-- *** Mustache is null ***
        // ......
       }
);

正如你在app.js文件的評論中看到的那樣, Mustache is null ...
我應該使用另一個胡子庫嗎? 這就是我使用的胡子

從2004年7月開始,看起來Mustache 支持AMD模塊 所以現在應該使用諸如require.js之類的加載器開箱即用。

您應該在您的胡子目錄中創建一個新文件mustache-wrap.js,如下所示:

 define(['libs/mustache/mustache'], function(Mustache){
    // Tell Require.js that this module returns a reference to Mustache
    return Mustache;
 });

然后你的主要是:

  mustache: "libs/mustache/mustache-wrap"

在發布此問題(以及答案)時不確定RequireJS 2.1.0是否已用完,但現在處理此問題的首選方法是使用shim config元素( 項目文檔頁面上的更多信息)。

你的main.js會變成:

require.config({
    paths: {
        jquery: 'libs/jquery/jquery',
        underscore: 'libs/underscore/underscore-min',
        backbone: 'libs/backbone/backbone-optamd3-min',
        mustache: "libs/mustache/mustache"
    },
    shim: {
        'mustache': {
            exports: 'Mustache'
        }
    }
});
(...)

這與包裝器建議@AntoJs 實際上相同,但沒有樣板代碼。

...但是,由於Mustache支持AMD,所以首先不需要包裝/墊片!

您也可以在使用小胡子的代碼中執行內聯命名的define,或者在“main.js”中的某處執行(省去了創建* -wrap文件的麻煩)

define('mustache', ['libs/mustache/mustache'], function(){
    // Tell Require.js that this module returns a reference to Mustache
    return Mustache; // from global
});
require(
    ['jquery','underscore','backbone','mustache']
    , function($, _, BB, Mustache){
        // use them
    }
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM