![](/img/trans.png)
[英]Can function in module.exports access global variable in module?
[英]I cannot access the variable in the other script. (Module.exports don't work everywhere)
我一直遇到module.exports問題。
我有 2 個使用Discord.js的腳本,並且我需要有一個兩個腳本通用的SetTimeout()變量才能從每個腳本中使用ClearTimeout() 。
我嘗試使用:
//first script
var foo = 20;
module.exports.foo = foo;
//Second Script
var exp = require('./firstscript');
console.log(exp.foo);
這是一個測試,用一個簡單的變量代替我的 SetTimeout(),看看我是否以錯誤的方式做這件事。
當我使用node命令運行新腳本時,測試運行良好
但是在我的 2 個原始腳本上使用npm 開始,它返回“未定義”,同時具有相同的語法。
在每個腳本中已經是Discord.js事件 class 的module.exports ,例如“Ready”。
我在聲明const的頂部的主module.exports之外運行這段代碼。
我想知道這是否導致了我的問題。
例子:
//the code i'm talking about is here.
module.exports = class ReadyEvent extends BaseEvent {
constructor() {
super('ready');
}
async run(client) {
謝謝你的幫助。
如果需要,請向我澄清。
編輯:
我在互聯網上查找是否是腳本中已經存在的 module.export 的問題。 確實如此。
顯然,如果每個模塊都沒有指定變量,則腳本中不能有多個module.export :
//this doesn't work
module.exports.value = value;
module.exports = value2;
//this works
module.exports.value = value;
module.exportd.value2 = value2;
我的問題是“discord.js 編譯器”使用已經存在的那個來注冊每個命令,所以我無法在不破壞機器人的情況下修改它。
我決定將我的計時器放在一個名為 GlobalVars 的新腳本中,它運行得非常好。
我很滿意它現在可以工作。
對我來說,問題已解決,但我很想知道是否可以使用 discord.js module.exports 語法導出變量。
從您的Second Script
變量來看,它似乎需要一個文件夾而不是文件,我認為不允許使用文件夾。
假設您需要腳本而不是文件夾:
第一個錯誤:要求時,括號內必須有引號( ""
)或( ''
)。
如果是文件夾,在./firstscript
旁邊加一個/
並將其分配給您要引用的文件。
var exp = require('./firstscript/THE_INTENDED_FILE');
...如果firstscript
是json
文件:
var exp = require('./firstscript.json');
從文件中提取變量
// Option 1:
console.log(exp.foo);
// Option 2:
const extract = exp.foo
console.log(extract);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.