如何使用 Node 16 在 Cypress 9 中导入插件?

How to import plugins in Cypress 9 with Node 16?


我正在努力尝试将外部库导入插件文件。
如果我做
const clipboardy = require('clipboardy')

它说“错误 [ERR_REQUIRE_ESM]:来自 /[...]/e2e/cypress/plugins/index.js 的 ES 模块 /[...]/e2e/node_modules/clipboardy/index.js 的 require()不支持。”。我也试过

import clipboardy from 'clipboardy'

但这仍然不起作用。我真的不知道怎么解决。
你能帮帮我吗?我在 node 16.10cypress 9.0.0 提前致谢

编辑:插件文件

const clipboardy = require("clipboardy");
const csv = require("node-xlsx").default;
const fs = require("fs");

const { lighthouse, pa11y, prepareAudit } = require("cypress-audit");

module.exports = (on, config) => {
  on("task", {
    parseXlsx({ filePath }) {
      return new Promise((resolve, reject) => {
        try {
          const jsonData = csv.parse(fs.readFileSync(filePath));
          resolve(jsonData);
        } catch (e) {
          reject(e);
        }
      });
    },

    getClipboard() {
      return clipboardy.readSync();
    },

    lighthouse: lighthouse(lighthouseReport => {
      const categories = lighthouseReport.lhr.categories;

      const audits = lighthouseReport.lhr.audits;

      const formattedAudit = Object.keys(audits).reduce(
        (metrics, curr) => ({
          ...metrics,
          [curr]: audits[curr].numericValue
        }),
        {}
      );

      const formattedCategories = Object.keys(categories).reduce(
        (metrics, curr) => ({
          ...metrics,
          [curr]: categories[curr].score * 100
        }),
        {}
      );

      const results = {
        url: lighthouseReport.lhr.requestedUrl,
        ...formattedCategories
      };

      console.log("Lighthouse results: [");
      console.log(results);
      console.log("]");

      //      fs.writeJSONSync("../results/audit.json", results);
      //      fs.writeFileSync(
      //        "audit.json",
      //        Buffer.from(JSON.stringify(results), "utf8")
      //      );
    }),

    pa11y: pa11y(pa11yReport => {
      console.log("pa11y results: [");
      console.log(pa11yReport);
      console.log("]");
    })
  });

  on("before:browser:launch", (browser, launchOptions) => {
    prepareAudit(launchOptions);

    if (browser.name === "chromium") {
      launchOptions.args.push(
        "--disable-features=CrossSiteDocumentBlockingIfIsolating,CrossSiteDocumentBlockingAlways,IsolateOrigins,site-per-process"
      );
      launchOptions.args.push(
        "--load-extension=cypress/extensions/Ignore-X-Frame-headers_v1.1"
      );
      launchOptions.args.push("--disable-dev-shm-usage");

      return launchOptions;
    }

    return launchOptions;
  });

  return config;
};

问题与剪贴板有关,它在版本 3 中变成了 ES Only 模数,与 Cypress 不兼容。降级到 v2.3 解决了这个问题