使用webpack输出ES模块

2024-05-07

使用 Rollup 我可以通过简单地设置来输出 ES 模块format选项'es'。我怎样才能用 webpack 做同样的事情?如果现在不可能的话,webpack 有计划添加吗?

我在里面唯一找到的东西的文档output.libraryTarget https://webpack.js.org/configuration/output/#output-librarytarget提到 ES 模块是这样的:

libraryTarget: "commonjs-module"- 使用暴露它module.exports目的 (output.library被忽略),__esModule已定义(它在互操作模式下作为 ES2015 模块进行线程化)

然而,我还不清楚。是不是一样libraryTarget: "commonjs2"唯一的区别是__esModule被定义为?什么是“互操作模式”?


首先我想说明一下两者的区别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";
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用webpack输出ES模块 的相关文章