Convert old JavaScript code into ES6 module
Asked Answered
H

1

1

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

Heartily answered 7/3, 2017 at 13:38 Comment(4)
But, put some code, explain morePender
@pmirnd here you are. Still it is totally wrong, but I don't know how should I start :(Heartily
Normally this would be the job of the module loader. For example webpack and SystemJS have options to consume scripts that add themselves to the global scope (as tracking.js does). What are you using to load the ES6 module?Present
@Present I'm using webpackHeartily
P
0

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 itself 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 exclamation mark).

Present answered 7/3, 2017 at 14:5 Comment(3)
syntax changed (import * as tracking from 'exports-loader?tracking!tracking';) but it is workingHeartily
Ah yeah I forgot about that, thanks. Updated answer.Present
The question remains, however, for those of us using native module support in all modern browsers except chrome which will land soon. So how do we do as asked: convert an existing library to an es6 module? Possibly build a wrapper of some sort?Santoro

© 2022 - 2024 — McMap. All rights reserved.