简体   繁体   中英

How can I integrate mixpanel and requirejs?

I'm using RequireJS to load all my javascript as AMD modules. Specifically, I'm using the "shim" configuration to load non-AMD modules.

But I'm getting an 'undefined' object when I tried to load MixPanel.

Here are the relevant files, with my successfully shim'ed Stripe js for comparison.

main.js:

require.config({
    paths: {
        stripe: 'libs/stripe/stripe',
        mp: 'libs/mixpanel/mixpanel'
    },
    shim: {
        'stripe': {
            exports: 'Stripe'
        },
        'mp': {
            exports: 'MP'
        }
    }
 });

libs/stripe/stripe.js and libs/mixpanel/mixpanel.js both have (function () {})(); calls as their documentations recommend.

my payment.js (which wraps Stripe):

define(['jquery', 'stripe'], function ($, Stripe) {
    var key = "MY_KEY";
    Stripe.setPublishableKey(key);
});

my track.js (which wraps MixPanel):

define(['jquery', 'mp'], function ($, MP) {
    var token = "MY_TOKEN";
    MP.init(token);
});

I have found that the mix panel snippet, which I guess you use in libs/mixpanel/mixpanel.js is adding a asynchronous <script> tag which downloads the full mixpanel library. Since RequireJS prevents the mixpanel variable from being attached to the window, it is never updated.

I am still trying to figure out how to make it work and will edit this answer if I figure it out.

Edit:

I have found out that mixpanel expects to be able to reassign window.mixpanel . So in your case you could do something like:

define(['mixpanel'], function (MP) {
    window.mixpanel = MP;
    window.mixpanel.init('TOKEN');
    ...
});

And your handlers for mixpanel should then use window.mixpanel since that will be the real instance.

I'm not familiar with shim, but it seems that you should have

'mp': {
    exports: 'mixpanel'
}

since the Mixpanel library exposes that, not window.MP .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM