【问题标题】:how to import JS function inside cypress.config.js如何在 cypress.config.js 中导入 JS 函数
【发布时间】:2023-02-25 07:29:50
【问题描述】:

我有一个 email.js 文件,它有一个名为 email_func 的函数,我想在 cypress.config.js 文件内的“after:run”块中调用该函数。但是当我尝试导入时出现以下错误


Your configFile is invalid: D:\Cypress-automation\cypress-automation\cypress.config.js
It threw an error when required, check the stack trace below:
ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a '.js' file extension and 'D:\Cypress-automation\cypress-automation\package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.

在 email.js 文件中,我在下面导出了

const email_var = new emailClass();
module.exports = email_var;

在 cypress.config.js 中,我正在尝试像这样导入,但没有运气


const email_var = require('./cypress/support/email');

【问题讨论】:

    标签: javascript cypress es6-modules


    【解决方案1】:

    关于 javascript 模块,几乎有两种语言,较旧的 cjs 使用 require() 和较新的 es modules。

    由于您在 package.json 中有 "type": "module",因此您选择了后者。

    因此,cypress.config.js 已经有了

    import { defineConfig }  from 'cypress'
    
    export default defineConfig({
      ...
    

    你需要使用import来代替email.js

    import { defineConfig }  from 'cypress'
    import email_var from './cypress/support/email.js'
    
    export default defineConfig({
      ...
    

    另外,您需要以 es-modules 样式导出

    const email_var = new emailClass();
    // module.exports = email_var;
    export default email_var;
    

    有关更一般性的讨论,请参阅Why is 'type: module' in package.json file?

    【讨论】:

      猜你喜欢
      • 2021-07-08
      • 2019-10-04
      • 2022-01-18
      • 2020-07-02
      • 2020-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-01
      相关资源
      最近更新 更多