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

迁移至Vitest遇CommonJS依赖读取失败问题求助

Vitest迁移中CommonJS依赖测试失败的处理方案

问题场景

迁移到Vitest后,某一项测试因读取依赖中的CommonJS文件失败,其他未导入该文件的测试正常运行。

当前vitest.config.ts配置:

import graphql from '@rollup/plugin-graphql';
import react from '@vitejs/plugin-react';
import { defineConfig } from 'vitest/config';

export default defineConfig({
  plugins: [
    graphql(),
    react()
  ],
  test: {
    environment: 'jsdom',
    deps: {
      registerNodeLoader: true,
      fallbackCJS: true,
    },
  },
});

收到的错误信息:

ReferenceError: exports is not defined in ES module scope
This file is being treated as an ES module because it has a '.js' 
file extension and '/Users/nadavnassi/Desktop/dev/admin-client/node_modules/@rapidapi/ui-lib-icons/package.json' 
contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.

解决方法

1. 强制转译问题依赖

给Vitest配置添加inline选项,将报错的@rapidapi/ui-lib-icons包纳入转译范围,让Vitest直接处理该依赖的模块格式冲突:
修改vitest.config.ts的test.deps部分:

test: {
  environment: 'jsdom',
  deps: {
    registerNodeLoader: true,
    fallbackCJS: true,
    inline: ['@rapidapi/ui-lib-icons'] // 新增此行
  },
},

2. 临时修改依赖配置

找到node_modules/@rapidapi/ui-lib-icons/package.json,删除其中的"type": "module"字段,或者将其改为"type": "commonjs"。注意该方案在每次执行npm install/yarn install后会被覆盖,仅适合临时测试使用。

3. 指定优先解析CommonJS入口

若该依赖本身提供了CommonJS格式的入口文件,可以在Vitest配置中添加resolve.conditions,让模块解析器优先读取CommonJS版本:

export default defineConfig({
  plugins: [graphql(), react()],
  resolve: {
    conditions: ['require', 'node'] // 优先处理CommonJS模块
  },
  test: {
    environment: 'jsdom',
    deps: {
      registerNodeLoader: true,
      fallbackCJS: true,
    },
  },
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 07:05:27