You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Rollup打包库的命名导出导入到HTML页面中

问题原因

你当前Rollup配置的输出格式为umd,该格式仅兼容CommonJS、AMD加载规范以及全局变量挂载场景,不支持浏览器原生ES模块的导入语法,所以你在type="module"的script标签中直接import该umd产物时,浏览器的ES模块加载器无法识别到内部的命名导出,就会触发报错。

解决方案

方案1:适配ES模块导入场景(推荐)

修改Rollup配置,输出esm(ES模块)格式的产物,即可直接适配浏览器原生导入逻辑:
修改rollup.config.js如下:

export default [
  // 保留umd格式输出,兼容非ES模块的旧场景使用
  {
    input: "min-example.js",
    output: {
      file: `min-example.umd.js`,
      name: "min-example",
      format: "umd"
    }
  },
  // 新增esm格式输出,供ES模块场景导入
  {
    input: "min-example.js",
    output: {
      file: `min-example.esm.js`,
      format: "es"
    }
  }
];

打包后在HTML中导入esm格式的产物即可正常使用:

<script type="module">
  import { minExample } from './min-example.esm.js';
  console.log(minExample());
</script>

方案2:沿用umd产物的原生使用方式

如果不需要使用ES模块导入,可直接通过umd默认挂载的全局变量调用产物:

<!-- 先引入umd产物,会自动在window上挂载min-example对象 -->
<script src="./min-example.bundle.js"></script>
<script>
  console.log(window['min-example'].minExample());
</script>

内容的提问来源于stack exchange,提问作者nvcleemp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 10:24:00