繁体   English   中英

Node.js 出口返回未定义

[英]Node.js exports return undefined

我有以下模块:

exports.CONSTANT = "aaaa";

function a() { ... }

module.exports = { a };

由于某些原因,当我这样导入时:

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

方法“a”已定义,但常量“CONSTANT”未定义

为什么会这样?

module.exports覆盖第一个export并在最后从require()调用返回。 如果你放一些日志:

exports.CONSTANT = "aaaa";

function a() {}

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

module.exports = { a };

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

尝试这个:

const CONSTANT = "aaaa";

function a() {}

module.exports = { CONSTANT, a };

或这个:

export const CONSTANT = "aaaa";

export function a() {}

您正在重新分配 module.exports 的值。 要解决此问题,您可以执行以下操作:


function a() { ... }

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

// OR

module.exports.CONSTANT = "aaaaa";

function a() { ... }

module.exports.a = a;

不幸的是,无法以这种方式拟合多个变量{ CONSTANT, a} ,因此我建议您以这种方式拟合多个变量:

{ 
     var1,
     var2,
}

例如:

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

暂无
暂无

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

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