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

Svelte Web Components导出类问题:无法从bundle.js导入TableSort

解决Svelte+Rollup中无法导出TableSort类的问题

这个问题其实是两个关键点导致的:你的main.ts没有对外导出TableSort,同时当前Rollup配置的输出格式(iife)不支持ES模块的import语法。下面一步步帮你解决:

1. 先在main.ts中导出需要外部访问的成员

Rollup只会打包你明确导出的内容到bundle的对外接口里。现在你的main.ts只是导入了TableSort,但没把它暴露出去,所以先修改main.ts:

import MinimalTableManager from './components/MinimalTableManager.svelte';
import MinimalDataTable from './components/MinimalDataTable.svelte';
import {TableSort} from './models/tableSort';

// 导出所有需要外部访问的组件和类
export { MinimalTableManager, MinimalDataTable, TableSort };

2. 修改Rollup配置,支持ES模块导出

你当前用的iife格式是自执行函数,代码都包裹在局部作用域里,不会生成ES模块的导出语句,所以外部用import肯定找不到。推荐同时输出两种格式:一种保留原来的iife(兼容传统全局引用),另一种输出ES模块格式供import使用。

修改rollup.config.js的output部分为数组:

output: [
  {
    sourcemap: true,
    format: 'iife',
    name: 'app',
    file: 'public/build/bundle.js'
  },
  {
    sourcemap: true,
    format: 'es',
    file: 'public/build/bundle.esm.js'
  }
]

3. 在外部页面中导入ES模块版本的bundle

现在重新构建项目后,你就可以用ES模块语法导入TableSort了:

<script type="module">
  import { TableSort } from '/build/bundle.esm.js';
  
  // 这里就可以正常使用TableSort类了
  const sortManager = new TableSort(/* 参数 */);
</script>

补充说明

  • iife格式适合直接通过<script>标签引入,变量会挂载到你配置的name(这里是app)全局对象上,比如app.TableSort也能访问到。
  • es格式是标准的ES模块,支持现代浏览器的import/export语法,这也是你需要的导入方式。

内容的提问来源于stack exchange,提问作者K. Anye

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:38:11