将旧的JavaScript代码转换为ES6模块 [英] Convert old JavaScript code into ES6 module

查看:184
本文介绍了将旧的JavaScript代码转换为ES6模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将旧的JavaScript库转换为ES6兼容模块。
图书馆是tracking.js( https:/ /github.com/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 (https://github.com/eduardolundgren/tracking.js/blob/master/build/tracking.js) but all my results ends with: Cannot read property 'xxx' of undefined

有没有简单的方法来使用这样的模块?我正在尝试创建像 https://trackingjs.com/docs.html#这样的基本示例第2步

Is there any easy way to use such module? I'm trying to create just basic example like https://trackingjs.com/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模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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