运行Cypress测试时遭遇Webpack编译错误,寻求解决方案
?? 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

