我正在尝试将旧的JavaScript库转换为ES6兼容模块。 图书馆是tracking.js( https:/ /github/eduardolundgren/tracking.js/blob/master/build/tracking.js )但我的所有结果都以:无法读取未定义的属性'xxx'
I'm trying to convert an old JavaScript library into ES6 compatible module. The library is tracking.js (github/eduardolundgren/tracking.js/blob/master/build/tracking.js) but all my results ends with: Cannot read property 'xxx' of undefined
有没有简单的方法来使用这样的模块?我正在尝试创建像 trackingjs/docs.html#这样的基本示例第2步
Is there any easy way to use such module? I'm trying to create just basic example like trackingjs/docs.html#step-2
因为有更多代码请求。让我展示一个非工作示例(Vue.js组件的一部分):
Because there is a request for more code. Let me show one of the non-working examples (part of Vue.js component):
import tracking from 'tracking'; export default { created() { const colors = new tracking.ColorTracker(['magenta', 'cyan', 'yellow']); } };错误是 TypeError:_tracking2.default.ColorTracker不是构造函数
推荐答案你应该使用 exports-loader ,不需要修改库,加载器将在全局范围内查找变量,例如:
You should use the exports-loader, no modification of the library is necessary, the loader will look for the variable on the global scope, e.g:
import * as tracking from 'exports-loader?tracking!tracking';exports-loader需要知道如何在全局范围内访问模块(tracking.js指定)它的自我 window.tracking )。在这里你要告诉它使用exports-loader参数 tracking (在查询问号之后)加载模块 tracking (在解释标记之后)。
The exports-loader needs to know how to access the module on the global scope (tracking.js assigns its self to window.tracking). Here you're telling it to use the exports-loader with parameter tracking (after the query question mark) to load the module tracking (after the explanation mark).
更多推荐
将旧的JavaScript代码转换为ES6模块
发布评论