NodeJS 在webpack中使用浏览器导入

wmtdaxz3  于 2023-04-20  发布在  Node.js
关注(0)|答案(1)|浏览(171)

我正在使用webpack为shopify主题编译一个插件,该插件利用基于浏览器的模块<script type ='module'...></script>,允许您使用import {Drawer} from '/theme.js'导入通用功能,这很好用,除了我没有在我的webpack中包含theme.js,所以我得到了错误:

ERROR in external "/theme.js"
The target environment doesn't support dynamic import() syntax so it's not possible to use external type 'module' within a script

方案一

webpackIgnore:true中使用动态导入似乎是这样工作的:

import(/* webpackIgnore: true */ "/theme.js").then(() => {
...
});

但这并不理想,因为我们希望在代码中的其他地方导入其他实用程序和内容,而这些地方不能使用动态导入。

方案二

我尝试使用IgnorePlugin来匹配浏览器导入

new IgnorePlugin({
          resourceRegExp: /^\/theme.js$/
      })

其工作以移除初始错误,但仍具有以下运行时错误:

Error: Cannot find module "theme.js"

是否有更好的方法将webpack与浏览器模块混合使用,或者这不是正确的方法?

cbjzeqam

cbjzeqam1#

看起来关键是使用externalsType: 'module'沿着experiments.outputModule,所以我最终的webpack配置中有:

...
    experiments: {
      outputModule: true,
    },
    externalsType: 'module',
    externals: {
        'static.theme.js': 'https://cdn.shopify.com/.../static.theme.js'
    },
...

相关问题