RequireJS:何时使用“paths”和“packages”?

10

在RequireJS中,何时应该使用paths而不是packages?是否有最佳实践或者在某些情况下,我应该考虑使用其中之一?

我按照文档操作,得到了以下结果:

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

根据我的有限经验,你必须使用带有dev jquery的包,否则它无法从baseUrl/加载core.js和其他依赖项,而不是jquery/。 - Corey Alix
1个回答

10
单词packages指的是标准CommonJS,因为requirejs支持加载以CommonJS Packages目录结构组织的模块,并且这些模块本身应该采用RequireJS可以理解的模块格式。
路径配置既可以针对目录,也可以针对文件(.js、requirejs模块)。有点令人困惑,因为如您所述,可以使用packages来加载非标准的CommonJS包。

我何时使用modules?

在requirejs中,所有定义在define('name', callback);内部的内容都是一个模块。
希望这个答案能够帮助你。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接