Convert old JavaScript code into ES6 module

2019-03-01 07:13发布

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条回答
\"骚年 ilove
2楼-- · 2019-03-01 07:30

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

查看更多
登录 后发表回答