首先我想说明一下两者的区别commonJS
and commonJS2
CommonJS
不支持使用module.exports = function() {}
这是由node.js
和许多其他commonJS
实施。
Webpack2
采用捆绑库代码的概念,为了广泛使用它,并使其兼容在不同环境中工作,我们使用--库目标 https://webpack.js.org/guides/author-libraries/#add-librarytarget option
现在这里的部分将回答您的两个问题
支持的可能库选项webpack2
are
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 and ES6模块,当导出一个default export
没有其他exports
module.exports
除了将被设置exports["default"]
如下例所示
export default test;
exports["default"] = test;
module.exports = exports["default"];
所以基本上这意味着commonJS-module
可以使用exposing it as module.exports
通过使用interloping
with ES2015 模块封装在 commonJS 中
有关的更多信息interloping
可以在这个找到blogpost https://medium.com/@kentcdodds/misunderstanding-es6-modules-upgrading-babel-tears-and-a-solution-ad2d5ab93ce0#.okohqovy3和堆栈溢出link https://stackoverflow.com/questions/33505992/babel-6-changes-how-it-exports-default to it.
基本思想是在ES6
运行时导出和导入属性无法更改 but in commonJS
这很好用 as the 要求在运行时发生更改因此它有ES2015 is 穿插的与commonJS.
Update
网页包2 提供创建可以捆绑和包含的库的选项.
如果您希望您的模块可以在不同的环境中使用然后您可以通过添加库选项将其捆绑为库并将其输出到您的特定环境。中提到的程序docs https://webpack.js.org/guides/author-libraries/.
关于如何使用 commonjs-module 的另一个简单示例
这里需要注意的重要一点是babel
adds exports.__esModule = true
每一个es6 module
并在导入时要求_interopRequire
检查该属性。
__esModule = true
只需要设置为库导出。需要设置在exports
of the 输入模块. 内部模块不需要__esModule
,这只是一个 babel hack。
正如文档中提到的
__esModule
被定义(它的线程为ES2015模块输入interop mode)
用法如中提到的测试用例 https://github.com/webpack/webpack/commit/66edde657eda2344954700feb1c9ae6e376d7fdc
export * from "./a";
export default "default-value";
export var b = "b";
import d from "library";
import { a, b } from "library";