Search code examples
javascriptjqueryecmascript-6babeljsumd

How to transpile ECMA6 import of jQuery to a UMD wrapper with Babel?


I'm trying to use Babel to transpile ECMA6 import of jQuery to a UMD wrapper.

My ECMA6 sources look as follows:

import {jQuery as $} from jquery;

<payload>

and Babel transpiles this to:

(function (global, factory) {
  if (typeof define === "function" && define.amd) {
    define(['jquery'], factory);
  } else if (typeof exports !== "undefined") {
    factory(require('jquery'));
  } else {
    var mod = {
      exports: {}
    };
    factory(global.jquery);
    global.metisMenu = mod.exports;
  }
})(this, function (_jquery) {
  'use strict';

  var _jquery2 = _interopRequireDefault(_jquery);

  function _interopRequireDefault(obj) {
    return obj && obj.__esModule ? obj : {
      default: obj
    };
  }

  var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
    return typeof obj;
  } : function (obj) {
    return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  };

  function _classCallCheck(instance, Constructor) {
    if (!(instance instanceof Constructor)) {
      throw new TypeError("Cannot call a class as a function");
    }
  }

  <payload>(_jquery.jQuery);

  })

This code works fine in Node.js environment as require('jquery') takes jquery from node_modules.

However, in browser environment global.jquery (which is equivalent to window.jquery) is not defined - jquery imports itself as $ or jQuery, but not as jquery.

Are there any Babel settings to fix this?

My current .babelrc

{
    "presets": [
        ["env", {
            "modules": "umd",
            "loose": true
        }]
    ]
}

Solution

  • You should use the globals option in the transform-es2015-modules-umd plugin:

    {
      "plugins": [
        ["transform-es2015-modules-umd", {
          "globals": {
            "jquery": "jQuery"
          }
        }]
      ]
    }
    

    See the docs.