Convert old JavaScript code into ES6 module

邮差的信 提交于 2019-12-02 06:45:52

问题


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

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

Update

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']);
  }
};

And the error is TypeError: _tracking2.default.ColorTracker is not a constructor


回答1:


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';

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).



来源:https://stackoverflow.com/questions/42649796/convert-old-javascript-code-into-es6-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!