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

运行Cypress测试时遭遇Webpack编译错误,寻求解决方案

Fixing Cypress Webpack Compilation Error with ?? Operator

Hey there, I’ve run into this exact issue before—let’s get it sorted out! The problem here is that your Webpack setup isn’t handling the newer ES2020 syntax (specifically the nullish coalescing operator ??) used in the @testing-library/dom package. By default, most Webpack configs skip transpiling code in node_modules, but this library uses syntax that your current loaders don’t recognize.

Here’s how to fix it step by step:

1. Update Your Babel Configuration

First, make sure Babel is set up to transpile ES2020+ code. Create or edit your babel.config.json (or .babelrc) in the root of your project:

{
  "presets": [
    ["@babel/preset-env", {
      "targets": {
        "browsers": ["last 2 versions", "not dead"],
        "node": "current"
      }
    }]
  ]
}

2. Adjust Cypress Webpack Preprocessor to Transpile @testing-library

Since Cypress uses its own Webpack setup, you need to tell it to process the @testing-library packages instead of skipping them. For Cypress 10+ (your version is 10.7.0), edit your cypress.config.js:

const { defineConfig } = require('cypress');
const webpackPreprocessor = require('@cypress/webpack-preprocessor');

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      const webpackOptions = {
        module: {
          rules: [
            {
              test: /\.js$/,
              // Only exclude node_modules EXCEPT @testing-library packages
              exclude: /node_modules\/(?!@testing-library)/,
              use: {
                loader: 'babel-loader',
                options: {
                  presets: ['@babel/preset-env']
                }
              }
            }
          ]
        }
      };
      on('file:preprocessor', webpackPreprocessor({ webpackOptions }));
    },
  },
});

3. Install Missing Dependencies (If Needed)

If you don’t already have these packages installed, run this command to add them:

npm install --save-dev @babel/core @babel/preset-env babel-loader @cypress/webpack-preprocessor

Bonus: Check Version Compatibility

If the above doesn’t work, double-check that your @testing-library/cypress version is compatible with Cypress 10.7.0. You might need to downgrade to a version like 8.0.7 or 9.0.0 (versions aligned with Cypress 10’s release cycle). Run this to adjust:

npm install --save-dev @testing-library/cypress@8.0.7

That should resolve the Webpack compilation error by ensuring the ?? operator gets transpiled into syntax your environment understands.

内容的提问来源于stack exchange,提问作者Big-Zude

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 15:07:45