Bedis ElAcheche
Bedis ElAcheche

Reputation: 21

Babel - Different transpilation results when exporting es modules

Let's say I have two es modules myModule/A and myModule/B and I want to export them in my myModule/index file. I have to approches to do so:

- Approch A:

// myModule/index.es
import moduleA from './A';
import moduleB from './B';
export { moduleA, moduleB };


Babel will transpile the code like below:

'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.moduleB = exports.moduleA = undefined;

var _A = require('./A');

var _A2 = _interopRequireDefault(_A);

var _B = require('./B');

var _B2 = _interopRequireDefault(_B);

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

exports.moduleA = _A2.default;
exports.moduleB = _B2.default;

- Approch B:

// myModule/index.es
export { default as moduleA } from './A';
export { default as moduleB } from './B';


Babel will transpile the code like below:

'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _A = require('./A');

Object.defineProperty(exports, 'moduleA', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_A).default;
  }
});

var _B = require('./B');

Object.defineProperty(exports, 'moduleB', {
  enumerable: true,
  get: function get() {
    return _interopRequireDefault(_B).default;
  }
});

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


Can anyone explain why we have different results?. Thank you!

Upvotes: 2

Views: 393

Answers (1)

loganfsmyth
loganfsmyth

Reputation: 161457

They are different results because Babel 6 does a bad job of compiling these cases. In Babel 7.x, the module transformation plugins were rewritten from scratch and two examples produce identical output with that, as

"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
Object.defineProperty(exports, "moduleA", {
  enumerable: true,
  get: function get() {
    return _A.default;
  }
});
Object.defineProperty(exports, "moduleB", {
  enumerable: true,
  get: function get() {
    return _B.default;
  }
});

var _A = _interopRequireDefault(require("./A"));

var _B = _interopRequireDefault(require("./B"));

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

As noted by Bergi, the only functional difference between the two is that the first will create local variables named moduleA and moduleB, but since your example code never tries to use those imported variables anyway, there is no difference in the output.

Upvotes: 3

Related Questions