首先我想说明commonJS和commonJS2之间的区别
CommonJS 不支持 module.exports = function() {} 的使用,node.js 和许多其他 commonJS 实现都使用它。
Webpack2 采用了捆绑库代码的概念,为了广泛使用它并使其兼容在不同环境中工作,我们使用 --libraryTarget 选项
现在这里的部分将回答你的两个问题
webpack2 中支持的可能库选项是
libraryTarget: "umd", // enum
libraryTarget: "umd-module", // ES2015 module wrapped in UMD
libraryTarget: "commonjs-module", // ES2015 module wrapped in CommonJS
libraryTarget: "commonjs2", // exported with module.exports
libraryTarget: "commonjs", // exported as properties to exports
libraryTarget: "amd", // defined with AMD defined method
libraryTarget: "this", // property set on this
libraryTarget: "var", // variable defined in root scope
Interlop有以下含义
为了鼓励使用CommonJS和ES6模块,当导出一个default export而没有其他exports时,将设置module.exports除了exports["default"]如下例所示
export default test;
exports["default"] = test;
module.exports = exports["default"];
所以基本上这意味着 commonJS-module 可以通过 暴露 使用 module.exports 来使用 interloping 和 ES2015 封装在 commonJS 中的模块
有关interloping 的更多信息可以在此blogpost 和stackoverflow link 中找到。
基本思想是在ES6 运行时导出和导入属性不能更改,但在commonJS 这很好因为需要更改发生在运行时 因此它具有 ES2015 与 commonJS插入。
更新
Webpack 2 提供了创建可以捆绑和包含的库的选项。
如果您希望您的模块在不同的环境中使用,那么您可以通过添加库选项将其捆绑为一个库并将其输出到您的特定环境。 docs中提到的程序。
另一个关于如何使用 commonjs-module 的简单示例
这里要注意的重要一点是babel 将exports.__esModule = true 添加到每个es6 module 并在导入时调用_interopRequire 来检查该属性。
__esModule = true 只需要在库导出上设置。需要在入口模块的exports上设置。 内部模块不需要__esModule,它只是一个 babel hack。
如文档中所述
__esModule 被定义(它被线程化为 ES2015 Module in interop 模式)
test cases中提到的用法
export * from "./a";
export default "default-value";
export var b = "b";
import d from "library";
import { a, b } from "library";