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

使用cypress-firebase运行Cypress测试时出现Webpack编译错误

问题分析

你遇到的Webpack编译错误是因为cypress-firebase的ESM模块中使用了ES2020的可选链操作符?.,而Cypress默认的Webpack配置不会转译node_modules目录下的第三方包,导致Webpack无法识别该语法。

解决方案

方案1:切换到cypress-firebase的CommonJS版本

cypress-firebase包中同时提供了ESM(lib-esm)和CommonJS(lib)两种编译产物,后者是已转译兼容低版本JS环境的代码。修改cypress.config.js中的导入路径:

const { defineConfig } = require('cypress');
// 改用CommonJS版本的插件
const cypressFirebasePlugin = require('cypress-firebase/lib/plugin').plugin;
const admin = require('firebase-admin');

module.exports = defineConfig({
  e2e: {
    baseUrl: 'http://localhost:3000',
    chromeWebSecurity: false,
    setupNodeEvents(on, config) {
      return cypressFirebasePlugin(on, config, admin, { projectId: process.env.NEXT_PUBLIC_PROJECT_ID });
    },
  },
});

方案2:配置Cypress转译node_modules中的cypress-firebase

如果需要使用最新版本的cypress-firebase,可以通过Babel转译该包的代码:

  1. 安装必要依赖:
npm install --save-dev @babel/core @babel/preset-env babel-loader @cypress/webpack-preprocessor
  1. 在项目根目录创建babel.config.json:
{
  "presets": [
    [
      "@babel/preset-env",
      {
        "targets": {
          "node": "current"
        }
      }
    ]
  ]
}
  1. 修改cypress.config.js添加Webpack预处理器配置:
const { defineConfig } = require('cypress');
const webpackPreprocessor = require('@cypress/webpack-preprocessor');
const cypressFirebasePlugin = require('cypress-firebase').plugin;
const admin = require('firebase-admin');

module.exports = defineConfig({
  e2e: {
    baseUrl: 'http://localhost:3000',
    chromeWebSecurity: false,
    setupNodeEvents(on, config) {
      // 配置Webpack转译cypress-firebase
      const webpackOptions = {
        module: {
          rules: [
            {
              test: /\.js$/,
              // 排除node_modules但保留cypress-firebase
              exclude: /node_modules(?!\/cypress-firebase)/,
              use: { loader: 'babel-loader' },
            },
          ],
        },
      };
      on('file:preprocessor', webpackPreprocessor({ webpackOptions }));
      
      return cypressFirebasePlugin(on, config, admin, { projectId: process.env.NEXT_PUBLIC_PROJECT_ID });
    },
  },
});

方案3:降级cypress-firebase到兼容版本

如果以上方案都无法解决,可以尝试降级到未使用ES2020语法的旧版本(需确认与Firebase 9.15.0兼容):

npm install cypress-firebase@4.0.0

内容的提问来源于stack exchange,提问作者J. Whitehead

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 03:05:30