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

Cypress无法识别别名@,解析为Node模块报错求助

解决Cypress无法解析Next.js路径别名@的问题

问题原因

项目中Next.js通过tsconfig.json配置了@作为路径别名,但Cypress的Webpack编译环境未同步该配置,导致无法解析@/helpers/isServer这类路径,触发编译错误。

解决方案

方法1:手动添加Webpack别名配置

修改Cypress插件文件(cypress/plugins/index.js),手动为Webpack添加别名解析规则:

/// <reference types="cypress" />
const injectDevServer = require('@cypress/react/plugins/next');
const path = require('path');

module.exports = (on, config) => {
  injectDevServer(on, config);

  // 配置Webpack解析@别名,指向项目src目录
  on('webpack:config', (webpackConfig) => {
    webpackConfig.resolve.alias = {
      ...webpackConfig.resolve.alias,
      '@': path.resolve(process.cwd(), 'src')
    };
    return webpackConfig;
  });

  return config;
};

方法2:自动同步tsconfig路径配置(推荐)

若项目中别名规则较多,用插件自动同步tsconfig.json的配置更高效:

  1. 安装依赖:
npm install tsconfig-paths-webpack-plugin --save-dev
  1. 修改Cypress插件文件:
/// <reference types="cypress" />
const injectDevServer = require('@cypress/react/plugins/next');
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
const path = require('path');

module.exports = (on, config) => {
  injectDevServer(on, config);

  // 加载tsconfig里的路径别名配置
  on('webpack:config', (webpackConfig) => {
    webpackConfig.resolve.plugins = [
      ...(webpackConfig.resolve.plugins || []),
      new TsconfigPathsPlugin({
        configFile: path.resolve(process.cwd(), 'tsconfig.json')
      })
    ];
    return webpackConfig;
  });

  return config;
};

额外配置:让Cypress的TypeScript识别别名

如果测试文件中也用到@别名,需在cypress/tsconfig.json同步配置:

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "baseUrl": "../",
    "paths": {
      "@/*": ["src/*"]
    }
  },
  "include": ["**/*.ts", "**/*.tsx"]
}

验证

重启Cypress并重新运行E2E测试,Webpack编译错误应会消失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 03:06:40