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

从Jest迁移到Vitest后@azure/msal-react模块导入错误求助

问题:从Jest迁移至Vitest后遭遇@azure/msal-react模块兼容错误

错误信息

require() of ES Module <path>\rush\common\temp\node_modules\.pnpm\@azure+msal-react@2.0.22_r\node_modules\@azure\msal-react\dist\index.js from <path>\rush\packages\auth\dist\index.js not supported.
Instead change the require of <path>\rush\common\temp\node_modules\.pnpm\@azure+msal-react@2.0.22_r\node_modules\@azure\msal-react\dist\index.js in <path>\rush\packages\auth\dist\index.js to a dynamic import() which is available in all CommonJS modules.

当前Vitest配置

export default defineConfig(async ({ mode }) => {
   //...其他代码

return {
    //...其他配置
    test: {
       environment: 'jsdom',
       globals: true,
       setupFiles: ['./src/setupTests.ts'],
    }
}

解决方法

1. 正确配置模块Mock(解决vi.mock失效问题)

直接使用vi.mock("@azure/msal-react")可能因模块加载优先级问题不生效,需在setupTests.ts里用工厂函数手动模拟模块导出,确保测试前完成Mock:

// src/setupTests.ts
vi.mock("@azure/msal-react", () => ({
  // 根据第三方包X用到的导出项模拟,比如MsalProvider、useMsal等
  MsalProvider: ({ children }) => children,
  useMsal: () => ({
    instance: { acquireTokenSilent: vi.fn() },
    accounts: [],
  }),
  // 补充其他需要的导出内容
}));

同时在vite.config.ts的test配置中,标记该模块为外部依赖:

test: {
  //...原有配置
  deps: {
    external: ['@azure/msal-react'],
  },
}

2. 强制转换ES模块为CommonJS

通过插件将@azure/msal-react转为CommonJS格式处理:

  1. 安装依赖:
pnpm add @vitejs/plugin-commonjs -D
  1. 在vite.config.ts中配置插件和转换规则:
import commonjs from '@vitejs/plugin-commonjs';

export default defineConfig(async ({ mode }) => {
  return {
    //...其他配置
    plugins: [commonjs()],
    test: {
      //...原有配置
      transformMode: {
        web: [/\.[jt]sx$/],
      },
      resolve: {
        conditions: ['require', 'node'],
      },
    },
  };
});

3. 调整pnpm包导出条件(进阶方案)

在项目根目录的.npmrc中添加配置,强制@azure/msal-react优先使用CommonJS导出:

@azure/msal-react:exports=require

该配置会让pnpm优先加载该包的CommonJS版本(若存在),规避ES模块与CommonJS的加载冲突。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 19:05:07