【问题标题】:How can I define variables that can be accessed from different files using node.js?如何使用 node.js 定义可以从不同文件访问的变量?
【发布时间】:2019-10-06 23:31:21
【问题描述】:

我正在使用 Cucumber、Nightwatch / node.js 和 javaScript 自动化 e2e 场景。

我想定义可以从不同的 .js 文件访问的变量。目前在 globals/globals.js 文件中定义了一些变量,格式如下:

module.exports = {
    testVar: "testVariableDefinition",
}

一旦定义,我将通过以下方式访问它们:

var test = this.api.globals.testVar;

所以这意味着我想在一个不同于 globals.js 的文件中定义其他变量,然后再访问它们。这背后的原因是我无法在一个文件中定义所有变量,有点乱。

【问题讨论】:

  • 在与globals.js 相同的目录中,只需创建另一个名为globals_test.js 的文件,然后您可以在module.exportsmodule.exports = { test: require("./globals_test") }.. 等中使用它。所以这允许您将配置拆分为可管理的小文件。
  • @Keith 非常感谢您!它有效!

标签: javascript node.js automation nightwatch.js qa


【解决方案1】:

由于您已经导出了变量,您可以简单地 importrequire 在您想要使用的地方使用它。

// Assuming fileA.js and fileB.js are in the same directory
// fileA.js
module.exports = {
  testVar: "testVariableDefinition",
}

// fileB.js
const { testVar } = require('./fileA');

【讨论】:

    猜你喜欢
    • 2021-02-12
    • 2015-07-22
    • 2020-10-21
    • 1970-01-01
    • 2018-11-16
    • 2018-11-24
    • 2015-06-22
    • 1970-01-01
    • 2011-12-19
    相关资源
    最近更新 更多