在 ES10 中正确的使用 exports 和 module.exports
在 Node.js 中,我们经常用到 exports 和 module.exports 来导出模块,但是在 ES6 及之前版本中,它们并没有明确的规范和用法。在 ES10 中,exports 和 module.exports 已经有了更加清晰的定义和用法,本文将详细介绍它们的用法和注意事项。
exports 和 module.exports 的区别
首先,需要明确 exports 和 module.exports 的区别。在 Node.js 中,exports 是 module.exports 的一个引用,它们实际上指向同一个对象。但是,当你给 exports 赋值时,它就不再指向 module.exports,而是指向一个新的对象。因此,如果你想导出一个对象,最好使用 module.exports。
示例代码:
// module.js exports.foo = 'foo'; module.exports.bar = 'bar';
// main.js const obj = require('./module'); console.log(obj); // { foo: 'foo', bar: 'bar' }
在上面的示例中,我们同时使用了 exports 和 module.exports 导出了两个属性,最终导出的是一个包含这两个属性的对象。
正确使用 exports
在 ES10 中,exports 的用法已经有了更加明确的规定。exports 只能用于导出一个对象的属性或方法,不能直接给 exports 赋值,否则会失效。
示例代码:
// module.js exports.foo = 'foo'; exports.bar = 'bar'; exports = { baz: 'baz' }; // 错误用法,不会导出 baz 属性
// main.js const obj = require('./module'); console.log(obj); // { foo: 'foo', bar: 'bar' }
在上面的示例中,我们试图给 exports 赋值一个新的对象,但是这样做不会导出 baz 属性。正确的用法应该是使用 module.exports。
正确使用 module.exports
当你想导出一个对象时,最好使用 module.exports。如果你只想导出一个属性或方法,也可以使用 module.exports。
示例代码:
// module.js module.exports = { foo: 'foo', bar: 'bar' };
// main.js const obj = require('./module'); console.log(obj); // { foo: 'foo', bar: 'bar' }
在上面的示例中,我们使用了 module.exports 导出了一个包含两个属性的对象。
注意事项
在使用 exports 和 module.exports 时,需要注意以下几点:
在同一个模块中,不能同时使用 exports 和 module.exports 导出对象。
如果你想导出一个空对象,应该使用 module.exports = {},而不是 exports = {}。
如果你想导出一个函数或类,应该使用 module.exports,而不是 exports。
如果你想导出一个属性或方法,可以使用 exports 或 module.exports。
总结
在 ES10 中,exports 和 module.exports 已经有了更加明确的用法和规范。exports 只能用于导出对象的属性或方法,不能直接赋值。而 module.exports 可以导出任何类型的对象。在使用时,需要注意遵循正确的用法和注意事项。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/653c84ba7d4982a6eb6a1c97