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

如何在Cypress 10中配置clipboardy?遇ESM模块导入错误求助

解决Cypress 10中clipboardy的ESM模块导入错误

错误原因

clipboardy从v3版本开始改为纯ESM模块,而你的cypress.config.js是CommonJS格式,无法用require()直接导入ESM模块,因此触发了ERR_REQUIRE_ESM错误。


解决方案1:使用动态import()替代require

利用setupNodeEvents的异步特性,在函数内部动态导入clipboardy,无需修改文件格式。修改后的配置代码如下:

const { defineConfig } = require("cypress");
const createBundler = require("@bahmutov/cypress-esbuild-preprocessor");
const addCucumberPreprocessorPlugin =
  require("@badeball/cypress-cucumber-preprocessor").addCucumberPreprocessorPlugin;
const createEsbuildPlugin =
  require("@badeball/cypress-cucumber-preprocessor/esbuild").createEsbuildPlugin;

module.exports = defineConfig({
  e2e: {
    async setupNodeEvents(on, config) {
      const bundler = createBundler({
        plugins: [createEsbuildPlugin(config)],
      });

      on("file:preprocessor", bundler);
      await addCucumberPreprocessorPlugin(on, config);

      // 动态导入ESM格式的clipboardy
      const clipboardy = await import("clipboardy");

      on('task', {
        getClipboard () {
            return clipboardy.readSync();
        }
      });

      return config;
    },
    specPattern: "cypress/e2e/features/*.feature",
    baseUrl: "XXXXXXXXXXXXX",
    chromeWebSecurity: false,
  },
});

解决方案2:降级clipboardy到CommonJS兼容版本

如果不想修改代码结构,可以安装clipboardy的v2.x版本(该版本仍支持CommonJS):

npm uninstall clipboardy
npm install clipboardy@2.3.0

安装完成后,原有的require("clipboardy")导入方式即可正常使用。


验证配置有效性

在测试用例中调用自定义task获取剪贴板内容:

cy.task('getClipboard').then(clipboardContent => {
  expect(clipboardContent).to.equal('预期的剪贴板内容');
});

内容的提问来源于stack exchange,提问作者AfiqSyed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 04:57:33