首页 > 解决方案 > 在nodejs中导出变量时出错

问题描述

我想导出一个变量。但这会发生

第一个文件

const commando = require('discord.js-commando');
const ytdl = require('ytdl-core');


class testCommand extends commando.Command {
    constructor(client) {
        super(client,{
            name: 'test',
            group: 'music',
            memberName: 'test',
            description: 'test',
        });

    }

    async run(message, args) {

        var Testo = 'hello'

    }

}

module.exports.Testo = Testo;
module.exports = testCommand;

第二个文件

const commando = require('discord.js-commando');
const ytdl = require('ytdl-core');
var Testotest = require('./test.js')


class pauseCommand extends commando.Command {
    constructor(client) {
        super(client,{
            name: 'pause',
            group: 'music',
            memberName: 'pause',
            description: 'Pause music',
        });

    }


    async run(message, args) {

        message.channel.send(Testotest.Testo())

    }

}

module.exports = pauseCommand;

错误

ReferenceError: Testo is not defined
    at Object.<anonymous> (/Users/andrew/Desktop/NullBot_/commands/music/test.js:27:24)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/Users/andrew/Desktop/NullBot_/commands/music/pause.js:3:17)
    at Module._compile (module.js:652:30)

为什么会报错?

标签: javascriptnode.jsnode-modules

解决方案


如果你运行方法,你Testo在方法中定义,但是你定义,所以,你需要运行一次方法来定义。runrun Testo = 'hello'class testCommandTestoundefinedrunTesto

这段代码

module.exports.Testo = Testo;

module.exports = {Testo: Testo}

但你用

module.exports = testCommand;

module.exports = testCommand

当你打电话时Testotest.TestotestCommand.Testo未定义)

更改第一个文件中的代码:

module.exports = testCommand;
module.exports.Testo = Testo;

推荐阅读