2013-08-06 33 views
8

什麼時候應該在RequireJS中使用pathspackages?有沒有最佳做法,或有特定的時間,我應該考慮使用一個在另一個?RequireJS:何時使用'路徑'與'包'

我跟着文檔,我想出了這個:

// main.js 
requirejs.config({ 
    enforceDefine: true, 
    urlArgs: "bust=" + (new Date()).getTime(), 
    baseUrl: "./js", 
    waitSeconds: 7, 
    paths: { 
     "jquery":  [ 
         'jquery' 
         ], 
     "underscore": [ 
         'underscore' 
         ], 
     "backbone": [ 
         'backbone' 
         ], 
     "handlebars":  [ 
         'handlebars' 
         ] 
    }, 
    shim: { 
     "underscore": { 
      deps: [], 
      exports: "_" 
     }, 
     "backbone": { 
      deps: ["jquery", "underscore"], 
      exports: "Backbone" 
     }, 
     "handlebars": { 
      deps: [], 
      exports: "Handlebars" 
     } 
    } // End shim 

}); // End config 


// List all files; use 'define()' and not 'require()' because of shim 
define([ 
    'jquery', 
    'underscore', 
    'backbone', 
    'handlebars' 
], function ($, _, Backbone, Handlebars) 
    { 
     console.log("$: " + typeof $); 
     console.log("_: " + typeof _); 
     console.log("Backbone: " + typeof Backbone); 
     console.log("Handlebars: " + typeof Handlebars); 
    } 
); // End define 

不過,我認爲從傑西·沃登(http://css.dzone.com/articles/video-basics-requirejs)的視頻,他似乎用這種風格他的大部分代碼:

// main.js 
requirejs.config({ 
    urlArgs: "bust=" + (new Date()).getTime(), 
    baseUrl: "./js", 
    waitSeconds: 7, 
    packages: [ 
       'main', 
       { 
        name: 'jquery', 
        location: 'libs/jquery', 
        main: 'jquery' 
       }, 
       { 
        name: 'underscore', 
        location: 'libs/underscore', 
        main: 'underscore' 
       }, 
       { 
        name: 'backbone', 
        location: 'libs/backbone', 
        main: 'backbone' 
       }, 
       { 
        name: 'handlebars', 
        location: 'libs/handlebars', 
        main: 'handlebars' 
       } 
    ] 
}); // End config 

那麼哪種方法是正確的呢?我應該使用paths還是packages?另外,還有一個modules配置。我何時使用modules

+0

從我有限的經驗來看,你必須使用dev jquery包,否則它將無法從baseUrl /而不是jquery /加載core.js和其他依賴。 –

回答

8

packages涉及標準CommonJS,因爲requirejs支持加載CommonJS Packages目錄結構中的模塊,並且模塊本身應該是RequireJS能夠理解的模塊格式。

路徑配置可以用於目錄和文件(.js,requirejs模塊)。有點令人困惑,因爲正如你所說的,你可以使用包加載非標準的CommonJS包。

什麼時候使用模塊?

一切都在中聲明requirejs:define('name', callback);是一個模塊

希望這個答案幫助。