简体   繁体   English

如何导出 function 中的常量? - ReactJS

[英]how to export a constant which is inside a function? - ReactJS

In a file called File_A.js I have a function that contains a constant.在一个名为File_A.js的文件中,我有一个包含常量的 function。 I want to export this const, and only this one (not the whole function) in order to use the constant's value in another file called File_B.js .我想导出这个常量,并且只导出这个常量(不是整个函数),以便在另一个名为File_B.js的文件中使用常量的值。 I tried to use module.exports but it returns that the variable is undefined.我尝试使用module.exports但它返回变量未定义。 Below a simplified example.下面是一个简化的例子。 Thanks谢谢

 // 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( /*...*/ ); }

how to export a constant which is inside a function?如何导出 function 中的常量?

There are two answers to this:对此有两个答案:

  1. You don't.你不知道。 It doesn't make sense.这没有意义。 Instead, you move the constant out of the function and export it.相反,您将常量移出 function 并将其导出。

  2. You do it exactly as you have done, but the constant won't be in the module's exports until MyFunctionA has been executed at least once.你完全按照你所做的那样做,但是在MyFunctionA至少执行一次之前,常量不会出现在模块的导出中。 This is possible because the CommonJS-style modules that you're using are dynamic and can change at runtime.这是可能的,因为您正在使用的 CommonJS 样式模块是动态的,可以在运行时更改。 However, making your exports dependent on a function call is asking for trouble, as you've discovered.但是,正如您所发现的那样,使您的导出依赖于 function 调用是自找麻烦。

So taking #1 on board, we get:所以考虑#1,我们得到:

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

A couple of notes on that:一些注意事项:

  1. MyFunctionA still closes over the constant and references it exactly the way it used to. MyFunctionA仍然关闭常量并完全按照以前的方式引用它。

  2. myVariable doesn't become a global, because the top-level scope of a CommonJS module isn't global scope. myVariable不会成为全局变量,因为 CommonJS 模块的顶级 scope 不是全局变量 scope。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM