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

如何配置Vite+Svelte项目,让打包后的JS模块导出指定内容

问题:Vite + Svelte(TS)打包后模块无导出,无法适配single-spa

核心需求

配置npm create vite@latest创建的Vite + Svelte(TypeScript)项目,让打包后的JS模块能导出指定内容,而非纯副作用模块。

详细背景

正在用single-spa改造微前端应用,计划将原React技术栈的根shell项目迁移到Svelte:

  • 已创建不带SvelteKit的Vite + Svelte应用,预留微前端加载位置,安装single-spa后调用registerApplication()和start(),根项目运行正常。
  • 测试微前端通过npm create vite@latest创建Svelte + TS项目,安装single-spa-svelte后,在main.ts中按要求导出三个生命周期函数:
import singleSpaSvelte from "single-spa-svelte";
import App from './App.svelte';
import './app.css';

const lc = singleSpaSvelte({
  component: App,
});

export const bootstrap = lc.bootstrap;
export const mount = lc.mount;
export const unmount = lc.unmount;
  • 打包后将带哈希的JS文件路径填入根项目的registerApplication(),但运行后微前端无法加载,动态import()返回的模块对象无任何导出内容,推测是Vite默认打包成了纯副作用模块。

解决方案

要让Vite打包后的模块保留导出内容,需修改Vite配置并调整代码细节:

1. 修改Vite配置文件(vite.config.ts)

开启库模式,指定打包输出为可被外部导入的模块格式:

import { defineConfig } from 'vite'
import { svelte } from '@sveltejs/vite-plugin-svelte'

export default defineConfig({
  plugins: [svelte()],
  build: {
    // 开启库模式,指定微前端入口文件
    lib: {
      entry: 'src/main.ts',
      name: 'Spa01MicroApp', // UMD格式下的全局变量名
      formats: ['es', 'umd'], // 输出ES模块和UMD两种格式,适配不同场景
      fileName: (format) => `spa01.${format}.js`
    },
    rollupOptions: {
      // 禁用默认HTML入口(微前端不需要独立页面)
      input: 'src/main.ts',
      output: {
        // 映射外部依赖的全局变量(如果有)
        globals: {
          'single-spa-svelte': 'singleSpaSvelte'
        }
      }
    }
  }
})

2. 修正TypeScript导出语法

原代码中export bootstrap = ...是错误语法,需改为export const bootstrap = ...(已在示例代码中修正),否则TS编译会直接报错,导致导出逻辑失效。

3. 调整打包与引用路径

  • 执行npm run build后,打包产物会输出到dist目录,生成spa01.es.js和spa01.umd.js两个文件。
  • 在根项目的registerApplication()中,引用ES模块路径即可:
registerApplication(
    'spa01',
    () => import('http://localhost:4173/dist/spa01.es.js'),
    '/spa01',
    { domEl: document.getElementById('spa01') }
);

额外说明

  • 若需优化依赖打包,可在rollupOptions.external中添加不需要打包进产物的外部依赖(比如single-spa-svelte),减少包体积。
  • Vite的preview命令默认托管dist目录,确保预览时能正确访问到打包后的模块文件。

内容的提问来源于stack exchange,提问作者José Ramírez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 11:35:31