将旧的JavaScript代码转换为ES6模块

编程入门 行业动态 更新时间:2024-10-26 04:22:52
本文介绍了将旧的JavaScript代码转换为ES6模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试将旧的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模块

本文发布于:2023-07-24 13:23:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1203696.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   模块   代码   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!