commonjs 和 commonjs2

作者: 赵永盛 | 来源:发表于2019-06-16 14:07 被阅读34次

webpack 中我们会看到:

那么,有什么区别呢?

commonjs: exports['MyLibrary'] = entry_return
commonjs2: module.exports = entry_return

exports 是 module.exports 的引用,所以不建议改变这个引用关系,所以我们不能直接:
exports = _entry_return_

这样 exports 不再指向 module.exports,我们直接 require 是不会导入任何内容的

只能是这种:
exports.xxx = yyy 或者 exports['xxx'] = yyy

相当于通过对象导出,增加了一层命名空间

使用的时候:
const MyLibrary = require('xxx').MyLibrary
或者:
const { MyLibrary } = require('xxx')

但是 module.exports 可以直接暴露 MyLibrary, 不用再加一层 MyLibrary 命名:
const MyLibrary = require('xxx')

关注我,每天更新技术干货!

相关文章

网友评论

    本文标题:commonjs 和 commonjs2

    本文链接:https://www.haomeiwen.com/subject/nuqgfctx.html