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

如何在Cypress中设置src目录为默认导入路径以避免依赖报错?

解决Cypress测试中的导入错误:将src目录设为默认路径

我之前也碰到过完全一样的问题——项目里用Webpack/Rollup把src/设为默认模块目录,写业务代码时import Bar from 'components/Bar'这类路径完全没问题,但一跑Cypress测试就疯狂报导入找不到的错误。下面是我亲测有效的解决方法,分不同场景说明:

针对Cypress 10+版本(当前主流版本)

修改项目根目录下的cypress.config.js(如果用TypeScript就是cypress.config.ts),给Webpack/Rollup添加模块解析配置,让它优先从src/目录查找模块:

如果你用Webpack作为构建工具

const { defineConfig } = require('cypress');
const webpack = require('webpack');

module.exports = defineConfig({
  // E2E测试配置
  e2e: {
    setupNodeEvents(on, config) {
      on('file:preprocessor', webpack({
        resolve: {
          // 把src目录加入模块解析的根路径列表
          modules: [`${config.projectRoot}/src`, 'node_modules']
        }
      }));
    },
  },
  // 组件测试配置(如果用的话)
  component: {
    devServer: {
      framework: 'react', // 替换成你的项目框架,比如vue/angular
      bundler: 'webpack',
      webpackConfig: {
        resolve: {
          modules: ['./src', 'node_modules']
        }
      }
    }
  }
});

如果你用Rollup作为构建工具

首先需要安装Cypress的Rollup预处理器:

npm install @cypress/rollup-preprocessor @rollup/plugin-node-resolve --save-dev

然后修改cypress.config.js:

const { defineConfig } = require('cypress');
const rollupPreprocessor = require('@cypress/rollup-preprocessor');
const resolve = require('@rollup/plugin-node-resolve');

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on) {
      on('file:preprocessor', rollupPreprocessor({
        plugins: [
          resolve({
            // 指定src为模块查找路径
            modulePaths: ['src']
          })
        ]
      }));
    },
  },
  // 组件测试同理,在devServer的rollupConfig里添加相同配置
  component: {
    devServer: {
      framework: 'react',
      bundler: 'rollup',
      rollupConfig: {
        plugins: [
          resolve({ modulePaths: ['src'] })
        ]
      }
    }
  }
});

针对Cypress 10以下的旧版本

修改cypress/plugins/index.js文件,配置预处理器的模块解析规则:

Webpack版本

const webpack = require('webpack');

module.exports = (on, config) => {
  on('file:preprocessor', webpack({
    resolve: {
      modules: [`${config.projectRoot}/src`, 'node_modules']
    }
  }));
  return config;
};

Rollup版本

同样先安装依赖,然后配置:

const rollupPreprocessor = require('@cypress/rollup-preprocessor');
const resolve = require('@rollup/plugin-node-resolve');

module.exports = (on, config) => {
  on('file:preprocessor', rollupPreprocessor({
    plugins: [
      resolve({ modulePaths: ['src'] })
    ]
  }));
  return config;
};

验证配置

配置完成后,重启Cypress测试 runner,再运行你的测试用例——之前那些指向src/下模块的导入应该就能被正确解析,不会再报错了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:53:09