简体   繁体   English

Node.js 出口返回未定义

[英]Node.js exports return undefined

I have the following module:我有以下模块:

exports.CONSTANT = "aaaa";

function a() { ... }

module.exports = { a };

For some reasons, when I import like this:由于某些原因,当我这样导入时:

const { CONSTANT, a } = require("./myModule");

the method "a" is defined, but the constant "CONSTANT" is undefined .方法“a”已定义,但常量“CONSTANT”未定义

Why is this happening?为什么会这样?

module.exports overrides the first export and gets returned from the require() call at the end. module.exports覆盖第一个export并在最后从require()调用返回。 If you put some logs:如果你放一些日志:

exports.CONSTANT = "aaaa";

function a() {}

console.log(module.exports); // {CONSTANT: "aaaa"}

module.exports = { a };

console.log(module.exports); // {a: ƒ a()}

Try this:尝试这个:

const CONSTANT = "aaaa";

function a() {}

module.exports = { CONSTANT, a };

Or this:或这个:

export const CONSTANT = "aaaa";

export function a() {}

You are reassigning the value of module.exports.您正在重新分配 module.exports 的值。 To fix this, you can do the following:要解决此问题,您可以执行以下操作:


function a() { ... }

module.exports = {
    CONSTANT: "aaaaa",
    a: a
}

// OR

module.exports.CONSTANT = "aaaaa";

function a() { ... }

module.exports.a = a;

Unfortunately, it is not possible to fit multiple variables in this way { CONSTANT, a} , so I recommend that you fit multiple variables in this way:不幸的是,无法以这种方式拟合多个变量{ CONSTANT, a} ,因此我建议您以这种方式拟合多个变量:

{ 
     var1,
     var2,
}

For example:例如:

const { 
     CONSTANT, 
     a
} = require("./Module");

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

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