素胚勾勒不出你
2023-09-28 16:50:53
在一個名為File_A.jsI 的文件中,有一個包含常量的函數(shù)。我想導出這個常量,并且只有這個常量(而不是整個函數(shù)),以便在另一個名為File_B.js. 我嘗試使用module.exports但它返回該變量未定義。下面是一個簡化的示例。謝謝// my function in File_A.jsconst MyFunctionA = () => { const myVariable = 'hello' module.export = {myVariable: myVariable} return ( /*...*/ );}// my second function in File_B.jsconst MyFunctionB = () => { const {myVariable} = require('./File_A.js'); console.log(myVariable) // undefined return( /*...*/ );}
1 回答

嗶嗶one
TA貢獻1854條經(jīng)驗 獲得超8個贊
如何導出函數(shù)內(nèi)部的常量?
對此有兩個答案:
你不知道。這沒有道理。相反,您可以將常量移出函數(shù)并將其導出。
MyFunctionA
您完全按照您所做的那樣進行操作,但是該常量在至少執(zhí)行一次之前不會出現(xiàn)在模塊的導出中。這是可能的,因為您使用的 CommonJS 樣式模塊是動態(tài)的并且可以在運行時更改。然而,正如您所發(fā)現(xiàn)的,使導出依賴于函數(shù)調(diào)用會帶來麻煩。
因此,采用#1,我們得到:
// my function in File_A.js
const myVariable = "hello"; // Odd name for a constant? ;-)
module.exports.myVariable = myVariable;
const MyFunctionA = () => {
return (
/*...*/
);
};
對此有幾點說明:
MyFunctionA
仍然關(guān)閉常量并按照以前的方式引用它。myVariable
不會成為全局范圍,因為 CommonJS 模塊的頂級范圍不是全局范圍。
添加回答
舉報
0/150
提交
取消