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

NX工作区Angular项目Cypress组件测试不识别customWebpackConfig

解决方案:Cypress组件测试不加载自定义Webpack配置(YAML Loader)

1. 修复配置路径拼写错误

先检查project.json中component-test目标的cypressConfig路径:

"cypressConfig": "apps/tes-application/cypress.config.ts"

这里存在拼写错误(tes-application应为test-application),会导致Cypress无法正确读取配置文件,间接影响自定义Webpack配置的加载。修正后:

"cypressConfig": "apps/test-application/cypress.config.ts"

2. 手动在Cypress配置中注入Webpack规则

如果修正路径后问题仍存在,可跳过依赖project.json的customWebpackConfig,直接在cypress.config.ts中修改Webpack配置:

方法A:直接添加YAML加载规则

修改cypress.config.ts,在component配置中扩展Webpack规则:

import { defineConfig } from 'cypress';
import { nxComponentTestingPreset } from '@nrwl/angular/plugins/component-testing';

export default defineConfig({
  e2e: { baseUrl: 'http://localhost:4000' },
  component: {
    ...nxComponentTestingPreset(__filename),
    viewportWidth: 1024,
    viewportHeight: 768,
    devServer: {
      ...nxComponentTestingPreset(__filename).devServer,
      webpackConfig: (config) => {
        // 添加YAML加载规则
        config.module.rules.push({
          test: /\.yaml$/,
          use: ['json-loader', 'yaml-loader']
        });
        return config;
      }
    }
  }
});

方法B:复用已有的webpack.custom.js

如果想复用现有的自定义Webpack配置文件,可导入并应用:

import { defineConfig } from 'cypress';
import { nxComponentTestingPreset } from '@nrwl/angular/plugins/component-testing';
import customWebpackConfig from '../../webpack.custom.js';

export default defineConfig({
  e2e: { baseUrl: 'http://localhost:4000' },
  component: {
    ...nxComponentTestingPreset(__filename),
    viewportWidth: 1024,
    viewportHeight: 768,
    devServer: {
      ...nxComponentTestingPreset(__filename).devServer,
      webpackConfig: (config) => {
        // 应用自定义Webpack配置
        return customWebpackConfig(config);
      }
    }
  }
});

3. 检查NX版本兼容性

部分旧版本的@nrwl/cypress组件测试预设存在未正确传递自定义Webpack配置的bug,建议升级到最新兼容版本:

npm update @nrwl/angular @nrwl/cypress

验证方法

启动组件测试后,可在Cypress界面确认配置是否生效:

  1. 打开Cypress组件测试界面
  2. 点击右上角Settings -> Webpack
  3. 检查module.rules中是否存在YAML相关规则

内容的提问来源于stack exchange,提问作者Martin-Mueller

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 01:31:04