导入后JavaScript类的static方法变为undefined问题咨询
为什么CommonJS模块导出的类在ES模块中导入后静态方法为undefined?
我编写了一个带有静态方法的JavaScript类,代码如下:
// test.cjs class Test { static init() { console.log('Test.init'); } } exports.default = Test; exports.Test = Test;
当我在ES模块文件中通过以下方式导入该类时:
// index.mjs const { default: x } = await import('./test.cjs'); console.log(x.init) // <- 输出`undefined`
问题原因
这是CommonJS与ES模块互操作的机制导致的:
- 在CommonJS模块中,
exports是module.exports的引用,当前代码最终会让module.exports变成一个包含default和Test两个属性的对象,而非Test类本身。 - 当ES模块导入CommonJS模块时,ES模块会将CommonJS的
module.exports作为该模块的默认导出值。也就是说你通过const { default: x } = await import('./test.cjs')拿到的x,其实是CommonJS模块的module.exports对象(即{ default: Test, Test: Test }),而非Test类。这个对象本身没有init静态方法,所以x.init返回undefined。
解决方法
有两种可行的修复方式:
方式1:修改CommonJS模块的导出逻辑
直接将Test类赋值给module.exports,让它成为模块的默认导出:
// test.cjs class Test { static init() { console.log('Test.init'); } } // 让module.exports指向Test类本身 module.exports = Test; // 可选:保留命名导出,方便其他CommonJS模块使用 module.exports.Test = Test;
此时在ES模块中导入后,x就是Test类,x.init可以正常访问静态方法。
方式2:在ES模块中正确解构目标类
直接从导入的模块命名空间中取命名导出的Test:
// index.mjs const { Test: x } = await import('./test.cjs'); console.log(x.init); // 正常输出静态方法
内容的提问来源于stack exchange,提问作者oxSaturn
相关产品推荐
相关产品推荐

