【问题标题】:load module in requirejs only in browser, not in nodejs仅在浏览器中加载requirejs中的模块,而不是在nodejs中
【发布时间】:2014-10-30 16:37:02
【问题描述】:

我使用 requirejs 为浏览器和 nodejs 编写了模块。

一切正常,但我想包含一个仅用于浏览器的模块,而不是用于节点,因为我不需要它并且它在节点中不起作用。 (它只是一个精美的浏览器设计库)。

我的代码如下所示:

define([
    'requirement',
    'libs/fancy'
], function(Requirement, fancy) {
    // do stuff
});

fancy 是我在 node.js 中不想要的库。所以我可以写一个这样的解决方法:

if (typeof window !== 'undefined') { // cheap detection of browser/node
    define([
        'requirement',
        'libs/fancy'
    ], start);
} else {
    define([
        'requirement'
    ], start);
}

function start(Requirement, Fancy) {
    // do stuff
}

但这显然是丑陋的。有谁知道更好的方法吗?

-- 编辑 1:

var requirements = ['requirement'];

if (typeof window !== 'undefined') {
    requirement.push('libs/fancy');
}

define(requirements, function(Requirement, Fancy) {
    // do stuff
}

还不完美

【问题讨论】:

    标签: javascript node.js requirejs


    【解决方案1】:

    我有时会使用您展示的第二种方法来创建一个依赖数组,我会根据我的需要推送这些依赖数组。

    但是,当我不想修改依赖项列表时,我使用了另一种方法。据推测,您模块中的代码必须使用undefined 的Fancy 值。因此,您可以使用以下内容。这个想法是配置 RequireJS 来加载一个模块,该模块在加载时返回一个 undefined 值。这样你就不需要修改你的依赖列表了。它只需要能够处理Fancy 未定义的情况。

    var requirejs = require("requirejs");
    
    // Create a fake module that we name immediately as "undefined".
    requirejs.define("undefined", [], function () { return undefined; });
    
    var req = requirejs.config({
        map: {
            // Make it so that all requests for `foo` load `undefined` instead.
            "*": {
                foo: "undefined"
            }
        }
    });
    
    req(["foo"], function (foo) {
        console.log(foo);
    });
    

    上面的例子将foo映射到undefined,所以当console.log执行时,控制台上的值是undefined。在您自己的代码中,您可以将 libs/fancy 映射到 undefined。

    此方法的一个变体是让undefined 模块返回一个对象,该对象显示与真实库相同的接口,但什么也不做。这将避免必须测试 Fancy 是否在您的模块中定义。不过,我会将假模块称为 undefined 以外的其他名称。也许像fake-fancy。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-05
      • 1970-01-01
      • 2023-03-08
      • 2013-12-10
      • 1970-01-01
      相关资源
      最近更新 更多