RequireJS:何时使用'paths'与'packages'

时间:2013-08-06 01:21:21

标签: javascript requirejs frontend amd

我应该何时在RequireJS中使用pathspackages?是否有最好的做法,或者在我应该考虑使用其中一个的特定时间?

我跟着文档,我想出了这个:

// 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

然而,我观看了Jesse Warden(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

1 个答案:

答案 0 :(得分:9)

单词packages指的是标准CommonJS,因为requirejs支持加载CommonJS Packages目录结构中的模块,模块本身应该是RequireJS可以理解的模块格式。

路径配置也可以是目录和文件(.js,requirejs模块)。有点混乱,因为如你所说,你可以使用包来加载非标准的CommonJS包。

  

我何时使用模块?

define('name', callback);内声明的requirejs中的所有内容都是一个模块

希望这个答案有所帮助。