【问题标题】:Cannot find module an external js whith fullpath after build a bundle whith Webpack and Babel in NodeJS在 NodeJS 中构建包含 Webpack 和 Babel 的捆绑包后,找不到具有完整路径的外部 js 模块
【发布时间】:2022-10-26 00:49:50
【问题描述】:

我使用包含 node_modules 的 Webpack 构建了一个包含所有需要资源的包,因为我将在另一个 package.json 和 node_modules 不存在的地方运行这个包,这就是我构建包含 node_modules 的包的原因。

在某些时候,捆绑包需要使用动态名称下载的外部 js,如果我将捆绑包移动到最终位置并使用 Node 运行它,当它尝试require('dynamic_fullpath.js') 时,日志会告诉Error: Cannot find module dynamic_fullpath.js ,文件(在本例中为:dynamic_fullpath.js)存在于正确的路径中。

我认为问题在于:Webpack 改变了需要js方法需要 webpack 方法并且在构建捆绑包时:dynamic_fullpath.js 不存在并且不添加到捆绑包中。

知道如何解决这种动态要求?

【问题讨论】:

    标签: javascript node.js webpack bundle


    【解决方案1】:

    最后是假设的问题:Webpack 将 require js 方法更改为需要 webpack 方法,并且在构建包时:dynamic_fullpath.js 不存在并且不添加到包中,因此,为了避免在特定要求上出现这种情况,我找到了这个解决方案,正如帖子所说:


    "

    在不诉诸 eval 的情况下实现这一目标的一种更简单的方法是:

    const requireFunc = typeof __webpack_require__ === "function" ? __non_webpack_require__ : require;
    const foo = requireFunc(moduleName);
    

    在捆绑的输出中,这将成为

    const requireFunc = true ? require : require;
    const foo = requireFunc(moduleName);
    

    "


    找到了解决方案here

    【讨论】:

      猜你喜欢
      • 2021-11-16
      • 1970-01-01
      • 1970-01-01
      • 2017-03-13
      • 2020-02-02
      • 1970-01-01
      • 2017-07-20
      • 2022-01-24
      • 2020-10-09
      相关资源
      最近更新 更多