Cypress从9升级到11后npx cypress run报错:无法解析node:perf_hooks
解决Cypress 11升级后
cypress run报错node:perf_hooks无法解析的问题 问题分析
报错核心是@cucumber/cucumber依赖Node.js内置模块node:perf_hooks,但Cypress默认的esbuild预处理器是针对浏览器环境打包的,无法识别Node内置模块的node:前缀语法。而cypress open运行正常是因为它采用实时编译,对模块解析的限制更宽松。
你的配置中还存在重复实例化NodeModulesPolyfillPlugin的冗余代码,这也可能干扰打包逻辑。
解决方案
步骤1:清理冗余配置
先删除重复的NodeModulesPolyfillPlugin实例,保持配置简洁:
const createEsbuildPlugin = require('@badeball/cypress-cucumber-preprocessor/esbuild'); const { NodeModulesPolyfillPlugin } = require('@esbuild-plugins/node-modules-polyfill'); // ... 其他代码 on( 'file:preprocessor', createBundler({ plugins: [NodeModulesPolyfillPlugin(), createEsbuildPlugin.default(config)], }), );
步骤2:添加Node内置模块Polyfill
安装专门处理Node全局对象和内置模块的插件:
npm install @esbuild-plugins/node-globals-polyfill --save-dev
修改配置,添加该插件并配置node:perf_hooks的别名映射,同时明确打包平台为浏览器:
const createEsbuildPlugin = require('@badeball/cypress-cucumber-preprocessor/esbuild'); const { NodeModulesPolyfillPlugin } = require('@esbuild-plugins/node-modules-polyfill'); const { NodeGlobalsPolyfillPlugin } = require('@esbuild-plugins/node-globals-polyfill'); // ... 其他代码 on( 'file:preprocessor', createBundler({ platform: 'browser', resolve: { alias: { 'node:perf_hooks': '@esbuild-plugins/node-globals-polyfill/shims/perf_hooks', }, }, plugins: [ NodeModulesPolyfillPlugin(), NodeGlobalsPolyfillPlugin({ process: true, buffer: true, }), createEsbuildPlugin.default(config), ], }), );
备选方案:切换打包平台(谨慎使用)
如果上述方法无效,可以尝试将esbuild的打包平台设置为node,强制以Node环境规则解析模块,但可能引发部分浏览器兼容性问题:
on( 'file:preprocessor', createBundler({ platform: 'node', plugins: [NodeModulesPolyfillPlugin(), createEsbuildPlugin.default(config)], }), );
关键说明
node:perf_hooks是Node.js 14.13.0+的内置模块,确保你的Node.js版本符合要求,过低版本需先升级Node。NodeGlobalsPolyfillPlugin用于模拟浏览器环境中缺失的Node全局对象(如process、Buffer),解决多数Node模块的依赖问题。
内容的提问来源于stack exchange,提问作者Stefano Borzì
相关产品推荐
相关产品推荐

