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

如何在Vitest中将类库暴露至全局window对象?

解决Vitest中全局暴露Node模块(如node-polyglot)的问题

你的核心问题是用错了Vitest的配置方式——define和alias无法模拟Webpack的expose-loader效果,正确的做法是在测试前置文件中手动将模块挂载到window对象:

步骤1:修改测试前置文件(test.setup.ts)

在你的test.setup.ts中导入目标模块,并将其挂载到全局window对象上,完全模拟expose-loader的行为:

// test.setup.ts
import Polyglot from 'node-polyglot';

// 挂载到window,让全局环境能访问到Polyglot构造函数
(window as any).Polyglot = Polyglot;

// 如果需要暴露jQuery,同理:
// import $ from 'jquery';
// (window as any).jQuery = $;
// (window as any).$ = $;

步骤2:清理无效的Vitest配置

删除之前错误添加的define和alias配置,你的最终vite.config.ts测试部分应保持简洁:

export default defineConfig({
    test: {
        globals: true,
        environment: "jsdom",
        setupFiles: "./test.setup.ts",
        css: true,
    }    
})

为什么之前的配置无效?

  • define: { Polyglot: true }:这个配置是把代码中所有Polyglot字符串替换成true,自然会导致new true()这种错误,完全不符合需求。
  • alias: { "Polyglot": './node_modules/node-polyglot' }:这只是路径别名,让你可以用import Polyglot from 'Polyglot'导入,但不会自动把变量暴露到全局window。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 22:30:03