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

Vite项目构建报错:UMD格式不支持顶级await,求解决方案

问题解决:Vite构建时RollupError(UMD不支持顶层await)

问题重现

构建Vite项目时触发RollupError,错误信息:

Module format "umd" does not support top-level await. Use the "es" or "system" output formats rather

代码中使用了顶层await,尝试替换为Promise链无法实现,相关代码和配置如下:

报错代码

// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

import { dotnet as dotnet2 } from './_framework/dotnet.js'

const dotnetEnv2 = await dotnet2
    .withDiagnosticTracing(false)
    .withApplicationArgumentsFromQuery()
    .create();

const setModuleImports_ideHelper = dotnetEnv2.setModuleImports;
const getAssemblyExports_ideHelper = dotnetEnv2.getAssemblyExports;
const getConfig_ideHelper = dotnetEnv2.getConfig;

setModuleImports_ideHelper('ide-helper.js', {});

var str = `&a = 5;
&b = 8;
if (&a > &b)
{
    &c = &a;
}
else if (&a == &b)
{
    &c = &a;
}
else
    &c = &b;`;

const config = getConfig_ideHelper();
export const exportsHelper = await getAssemblyExports_ideHelper(config.mainAssemblyName);

原Vite配置

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import tsconfigPaths from "vite-tsconfig-paths";
import { resolve } from "path"
import dts from "vite-plugin-dts"

export default defineConfig({
    plugins: [react(), tsconfigPaths(), dts({ rollupTypes: true })],
    build: {
        minify: false,
        lib: {
            entry: resolve(__dirname, "src/main.ts"),
            name: "ide",
            fileName: "ide"
        },
        rollupOptions: {
            external: [
                "react",
                "react-dom",
                "react/jsx-runtime",
            ],
            output: {
                globals: {
                    react: "React",
                    "react-dom": "ReactDOM",
                    "react/jsx-runtime": "react/jsx-runtime",
                },
                dir: 'dist',
                format: 'es',
                entryFileNames: "[name].js"
            },
        },
        target: "esnext",
    },
    esbuild: {
        target: "es2022"
    },
    optimizeDeps: {
        esbuildOptions: {
            target: "es2022",
        }
    },
    resolve: {
        alias: {
            '@src': resolve(__dirname, 'src'),
        },
    },
});

解决办法

1. 修正Vite配置,锁定ES输出格式

虽然配置中指定了output.format: 'es',但lib.name字段可能触发Rollup默认生成UMD兜底产物,需在lib配置中明确限定格式:

修改build.lib部分:

lib: {
    entry: resolve(__dirname, "src/main.ts"),
    name: "ide",
    fileName: (format) => `ide.${format}.js`, // 按格式生成文件名
    formats: ['es'] // 仅生成ES格式产物
},

确保rollupOptions.output.format与lib.formats保持一致,避免多格式冲突。

2. 调整代码结构,兼容异步导出(可选)

若需兼容更多运行环境,可将顶层await封装为初始化函数,通过Promise导出异步结果:

修改后的代码:

// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

import { dotnet as dotnet2 } from './_framework/dotnet.js'

let initPromise;
let exportsHelper;

// 初始化函数,缓存异步结果
export async function initIdeHelper() {
    if (initPromise) return initPromise;
    
    initPromise = (async () => {
        const dotnetEnv2 = await dotnet2
            .withDiagnosticTracing(false)
            .withApplicationArgumentsFromQuery()
            .create();

        const setModuleImports = dotnetEnv2.setModuleImports;
        const getAssemblyExports = dotnetEnv2.getAssemblyExports;
        const getConfig = dotnetEnv2.getConfig;

        setModuleImports('ide-helper.js', {});
        const config = getConfig();
        exportsHelper = await getAssemblyExports(config.mainAssemblyName);
    })();

    await initPromise;
    return exportsHelper;
}

// 导出获取helper的快捷方法
export const getExportsHelper = () => initPromise ? initPromise.then(() => exportsHelper) : initIdeHelper();

// 保留原字符串常量
export const str = `&a = 5;
&b = 8;
if (&a > &b)
{
    &c = &a;
}
else if (&a == &b)
{
    &c = &a;
}
else
    &c = &b;`;

3. 排查插件冲突

若修改配置后仍报错,可暂时禁用vite-plugin-dts的rollupTypes参数,确认是否为插件触发的额外Rollup构建导致UMD格式生成:

dts({ rollupTypes: false })

验证方案

执行npm run build,检查dist目录下仅生成ES格式产物(如ide.es.js),确认报错消失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 17:37:12