【问题标题】:how to export a constant which is inside a function? - ReactJS如何导出函数内部的常量? - 反应JS
【发布时间】:2020-12-02 11:05:13
【问题描述】:

在一个名为File_A.js 的文件中,我有一个包含常量的函数。我想导出这个常量,并且只导出这个常量(不是整个函数),以便在另一个名为File_B.js 的文件中使用常量的值。我尝试使用module.exports,但它返回变量未定义。下面是一个简化的例子。谢谢

// my function in File_A.js
const MyFunctionA = () => {

  const myVariable = 'hello'
  module.export = {myVariable: myVariable}

  return (
  /*...*/
  );
}

// my second function in File_B.js
const MyFunctionB = () => {

  const {myVariable} = require('./File_A.js');
  console.log(myVariable) // undefined

  return(
  /*...*/
  );
}

【问题讨论】:

  • 不是module.exports(带有s)吗?
  • module.export 应该在全局范围内,因为在调用 MyFunctionA 之前它不会被分配。
  • @PraveenKumarPurushothaman - 令人惊讶的是,使用 OP 使用的导出样式,您可以......这不是一个好主意。 :-)
  • 如果它是对不可变事物(在本例中为字符串)的 const 引用,只需将其从函数中移到顶层,就没有理由将其隐藏在闭包中。
  • @T.J.Crowder 谢谢老兄。这是我今天学到的新东西。

标签: javascript node.js reactjs react-native


【解决方案1】:

如何导出函数内部的常量?

对此有两个答案:

  1. 你没有。这没有意义。相反,您将常量移出函数并将其导出。

  2. 您完全按照以前的方式进行操作,但在 MyFunctionA 至少执行一次之前,该常量不会出现在模块的导出中。这是可能的,因为您使用的 CommonJS 样式的模块是动态的并且可以在运行时更改。但是,正如您所发现的,让您的导出依赖于函数调用是自找麻烦。

因此,将 #1 加入,我们得到:

// my function in File_A.js
const myVariable = "hello"; // Odd name for a constant? ;-)
module.exports.myVariable = myVariable;
const MyFunctionA = () => {
    return (
        /*...*/
    );
};

对此有几点说明:

  1. MyFunctionA 仍然关闭常量并完全按照以前的方式引用它。

  2. myVariable 不会成为全局范围,因为 CommonJS 模块的顶级范围不是全局范围。

【讨论】:

    猜你喜欢
    • 2020-07-01
    • 1970-01-01
    • 2020-08-05
    • 1970-01-01
    • 1970-01-01
    • 2012-05-31
    • 2018-10-12
    • 1970-01-01
    • 2018-11-26
    相关资源
    最近更新 更多