Node.js 导出 return 未定义

Node.js exports return undefined

我有以下模块:

exports.CONSTANT = "aaaa";

function a() { ... }

module.exports = { a };

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

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

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

为什么会这样?

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


function a() { ... }

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

// OR

module.exports.CONSTANT = "aaaaa";

function a() { ... }

module.exports.a = a;

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() {}

遗憾的是,这种方式无法拟合多个变量{ CONSTANT, a},所以我建议您采用这种方式拟合多个变量:

{ 
     var1,
     var2,
}

例如:

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