在ES6中导入ES5库 [英] import ES5 library in ES6

查看:418
本文介绍了在ES6中导入ES5库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在ES6上使用用ES5编写的库( rtree )项目,但没有运气.

I'm trying to use a libary written in ES5 (rtree) on a ES6 project but with no luck.

在我的ES6代码上,我这样做:

On my ES6 code i do:

 import PolygonLookup from '../../lib/rtree';
 ...
 this.rtree = new PolygonLookup(geojson);//does not work

这不起作用,但是,如果我删除了导入,而是将rtree添加到html的标签上,则可以正常工作.

This does not work, however if i remove the import and instead add the rtree on a tag to my html it works flawlessly.

 <script type="text/javascript" src="..\..\lib\rtree.js"></script>

 this.rtree = new PolygonLookup(geojson); //works

我试图通过lebab将上述库转换为ES6,但是它也不起作用.

I tried to convert the abovementioned library to ES6 through lebab but it also won't work.

推荐答案

ES5库不会以与ES6兼容的方式导出任何内容.这就是为什么未定义PolygonLookup的原因.您可以导入库而无需任何绑定:

An ES5 lib doesn't export anything in an ES6 compatible way. That's why PolygonLookup is undefined. You can import the library without any binding:

import '../../lib/rtree';

这样,PolygonLookup将成为全局PolygonLookup,就像您在库中添加了script标记 IF 一样,它已被添加为全局变量.并非所有的库都明确地这样做.否则,您可以尝试脚本加载器(仅适用于Webpack):

That way PolygonLookup will be the global PolygonLookup, just as if you included the lib with a script tag, IF it has been added as a global variable. Not all libraries do that explicitly. Otherwise you might try script-loader (Webpack only):

import 'script-loader!../../lib/rtree';
or even
import PolygonLookup from 'script-loader!../../lib/rtree';

如果您选择的捆绑器/装载器支持其他模块格式,并且库使用其中一种格式,那么您也可以使用常规的ES6导入.

If the bundler / loader of your choice supports other module formats, and the library uses one of them, then you could also use a regular ES6 import.

这篇关于在ES6中导入ES5库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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