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

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

本文关键字:webpack 加载 模块 返回 null 项目 require js      更新时间:2023-09-26

我试图在require.js项目中加载一个编译为Webpack的库。当库公开一个对象时,当require.js项目需要时,它返回null:

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

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

解决方案是在Webpack文档中:有一个outputLibrary标志,可以设置为"amd"或"umd",在这种情况下,Webpack产生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 */;
});

块,也许在一些构建后事件的帮助下(例如,在webpack的构建后插件中使用这个)。然后,您应该能够使用AMD加载器来要求该模块。

原始答:

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实例,有相关的文档。

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