在基于 require.js 的项目中加载 webpack 模块 returns null

Loading webpack module in a require.js based project returns null

我正在尝试在 require.js 项目中加载一个编译为 Webpack 的库。虽然库公开了一个对象,但在 require.js 项目需要时它 returns null :

define(function(require, exports, module) {
  [...]
  require("./ext/mylib.core.js"); // -> null
})

我可以在 Webpack 中使用任何标志来启用 AMD 合规性吗?在生成的库中有一些对 AMD 的引用,但实际上它似乎没有做任何事情。

编辑 3:/编辑:4 Webpack 似乎没有合作,所以另一种可能性是使用 shim 配置选项公开模块:

require.config({
    paths: {
        // Tell require where to find the webpack thingy
        yourModule: 'path/to/the/webpack/asset'
    },
    shim: {
        // This lets require ignore that there is no define
        // call but will instead use the specified global
        // as the module export
        yourModule: {
            exports: 'theGlobalThatIsPutInPlaceByWebpack'
        }
    }
});

这显然只适用于 webpack 东西将某些东西放在全局范围内的情况。希望这对您有所帮助!

编辑 2: 所以我在评论中指出了错误的问题。我没有找到任何从 webpack 生成 AMD 模块的内置功能——最终结果似乎是一个静态资产 js 文件。您可以将结果包装在

define(function () {
    return /* the object that webpack produces */;
});

块,可能在某些构建后事件的帮助下(例如使用 this after build plugin for webpack)。那么你应该能够使用 AMD 加载器来 require 模块。

原答案:

require.js 异步加载它的依赖项,当您不使用 r.js 优化器等时,您必须显式声明它们。因此,如果模块公开 AMD 定义,它应该像这样工作:

// It works the way you did it ...
define(['path/to/your/module'], function (require, exports, module) {
    require('path/to/your/module'); // -> { ... }
});

// ... but I personally prefer this explicit syntax + it is
// friendlier to a code minifier
define(['path/to/your/module'], function (yourModule) {
    console.log(yourModule); // { ... }
});

也许你需要配置你的require实例,有docs for that.

EDIT1: 正如所指出的那样,访问模块的方式并没有错,但是依赖项丢失了,所以我添加了更接近原始问题的代码。

解决方案在 Webpack 文档中:有一个 outputLibrary 标志可以设置为 "amd" 或 "umd",在这种情况下,webpack 会生成 amd 兼容模块。