通过 webpack 使用浏览器导入

问题描述 投票:0回答:1

我正在使用 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

解决方案1

使用动态导入与

webpackIgnore:true
似乎是这样工作的:

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

但这并不理想,因为我们还想在代码中无法使用动态导入的其他位置导入其他实用程序和内容。

解决方案2

我尝试使用

IgnorePlugin
来匹配浏览器导入

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

它可以消除初始错误,但仍然存在运行时错误:

Error: Cannot find module "theme.js"

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

node.js webpack import module webpack-4
1个回答
0
投票

似乎关键是使用

externalsType: 'module'
experiments.outputModule
所以我最终的 webpack 配置中有这个:

...
    experiments: {
      outputModule: true,
    },
    externalsType: 'module',
    externals: {
        'static.theme.js': 'https://cdn.shopify.com/.../static.theme.js'
    },
...
© www.soinside.com 2019 - 2024. All rights reserved.