commonjs - 如何通过Webpack和6to5使用带有es6模块的npm包?

标签 commonjs webpack javascript ecmascript-6

假设我想在我的项目(或任何给定的 npm 包)中使用 Immutable。我已经npm install编辑了它,所以它在node_modules中。当然,它有 CommonJS 导出。但是,我想在我的项目中使用 es6 模块。

我使用 Webpack 将其全部编译在一起,并使用 6to5-loader 来处理 es6 模块语法。

在我的源文件中,我说 import Immutable from 'immutable'; --- 但这会导致问题,因为 es6 import 正在寻找 es6 default 已导出,但事实并非如此(对于 Immutable 或可能几乎任何其他 npm 包)。编译后的代码最终看起来像这样: var Immutable = require('immutable')["default"]; --- 这当然会引发错误,因为没有 default 要查找的属性。

我可以使用带有 es6 模块的 npm 包吗?

最佳答案

Babel.js贡献者在这里。您正在寻找以下内容:

import * as Immutable from 'immutable';
// compiles to:
var Immutable = require('immutable');

Interactive demo

Note: This is with either the common or commonInterop modules option. For others, see: https://babeljs.io/docs/usage/modules/

关于commonjs - 如何通过Webpack和6to5使用带有es6模块的npm包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27305954/

相关文章:

javascript - module.exports 与 CommonJs 中的 "this"相同吗?

javascript - JsDoc 和 WebStorm : Refer to exports

json - common-js utils 中的 JSON Schema 验证是否支持引用?

javascript - 如何使用条件导入编写在浏览器和 Node 中都可以使用的 ESM 模块

javascript - 与 webpack 捆绑时,TTF 字体不会显示在浏览器中

javascript - 如何在 codeigniter 中将数据从 View 发送到 Controller

webpack - 如何启动并运行 webpack-serve?

reactjs - 在 ASP.NET Core 应用程序中配置 React Dev Server

javascript - Vue todolist 仅在一个列表上切换类

javascript - 隐藏 tr 元素以防止在其中单击