【发布时间】: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