如何通过Webpack和6to5消费具有es6模块的npm软件包? [英] How to consume npm package with es6 module via Webpack and 6to5?

查看:196
本文介绍了如何通过Webpack和6to5消费具有es6模块的npm软件包?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我正在使用Webpack一起编译,使用6to5加载器来处理es6模块语法。



在我的源文件中,我说'code> import immutable from'immutable'; ---但这会导致问题因为es6 import 正在寻找已经导出的es6 默认值,不是这样(对于Immutable或大概几乎任何其他npm包)。编译代码最终看起来像这样: var Immutable = require('immutable')[default]; ---当然会引发错误,因为有否默认属性来查找。



我可以使用es6模块的npm软件包吗?

解决方案

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

  import * as immutable from'immutable'; 
//编译为:
var Immutable = require('immutable');

Interactive demo


注意:这是与通用 commonInterop modules选项。有关其他信息,请参阅: https://babeljs.io/docs/usage/modules/



Let's say I want to use Immutable in my project (or any given npm package). I have npm installed it, so it is in node_modules. Of course, it has CommonJS exports there. I, however, want to use es6 modules in my project.

I am using Webpack to compile it all together, with the 6to5-loader to deal with es6 module syntax.

In my source file, I say import Immutable from 'immutable'; --- but this causes a problem because the es6 import is looking for an es6 default to have been exported, which isn't the case (for Immutable or probably almost any other npm package). The compiled code ends up looking like this: var Immutable = require('immutable')["default"]; --- which of course throws an error, since there is no default property to find.

Can I consume the npm packages with es6 modules?

解决方案

Babel.js contributor here. You're looking for the following:

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/

这篇关于如何通过Webpack和6to5消费具有es6模块的npm软件包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆