Error loading firebase js with requirejs

2019-03-03 04:43发布

问题:

I load Firebase js library with RequireJS like this:

require([
    'firebase-app',
    'firebase-storage'
], function (firebase) {
    firebase.initializeApp({...});
    firebase.storage();
});

Until Firebase js release 4.12.1 everything was ok, since 4.13.0 release I get these errors on "firebase.storage()" call:

TypeError: Cannot read property 'registerService' of undefined at firebase (index.esm.js:3442) at index.esm.js:3434

and

Uncaught Error: Cannot instantiate firebase-storage - be sure to load firebase-app.js first. at firebase (index.esm.js:3444) at index.esm.js:3434

In Firebase 4.13.0 release notes there is this the change I think is breaking my code: https://firebase.google.com/support/release-notes/js#version_4130_april_19_2018

[CHANGED] Refactored to use core-js for our Polyfills/Shims.

"core-js" is this library: https://github.com/zloirock/core-js

These are the jsfiddle examples:

  • library 4.12.1 - https://jsfiddle.net/ptmw0srq/27/ (the old and working one)
  • library 4.13.0 - https://jsfiddle.net/ptmw0srq/28/
  • library 5.4.0 - https://jsfiddle.net/ptmw0srq/30/
  • loading only the full js works again - https://jsfiddle.net/ptmw0srq/72/

回答1:

Found the solution at this page (valid only for firebase release >= 5.5.6):

https://github.com/firebase/firebase-js-sdk/issues/1266#issuecomment-441405513

you must call firebase.app.js like "@firebase/app", so:

var config = {
    paths: {
        '@firebase/app': 'https://www.gstatic.com/firebasejs/5.7.1/firebase-app',
        '@firebase/storage': 'https://www.gstatic.com/firebasejs/5.7.1/firebase-storage'
    }
};
require([
    '@firebase/app',
    '@firebase/storage'
], function (firebase) {
    firebase.initializeApp({
        ...
    });

    firebase.storage();
});

final jsfiddle: https://jsfiddle.net/ptmw0srq/125/