9

I'm writing a lib with webpack with these settings:

output: {
    path: path.join('build'),
    filename: 'my_lib.js',
    library: 'MyLib',
    libraryTarget: 'umd'
  },

MyLib:

export default function() {
  console.log('MyLib');
}

The problem is, when I try to load the build/my_lib.js in a browser, the only way to access MyLib is through MyLib.default...

Any idea?

gtournie
  • 4,143
  • 1
  • 21
  • 22

3 Answers3

18

You should set libraryExport to default;

https://webpack.js.org/configuration/output/#outputlibraryexport

Jack Pu
  • 524
  • 3
  • 11
8

the key is to use libraryExport: "default" like this:

  module.exports = {
    entry: ...,
    output: {
      path: __dirname + "/dist/",
      filename: "Template.js",
      library: "Template",
      libraryTarget: "umd",
      libraryExport: "default",
      globalObject: "this",
    },
Dorian
  • 7,749
  • 4
  • 38
  • 57
4

If you are asking about any idea of why?

If you are using Babel to enable ES6 features then you are probably facing one of the changes between Babel5 and Babel6.

With Babel5 your code is transpiled to this:

'use strict';

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

exports['default'] = function () {
  console.log('MyLib');
};

module.exports = exports['default'];

But with Babel6 you get:

'use strict';

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

exports.default = function () {
  console.log('MyLib');
};

Do you spot the difference?

module.exports = exports['default'];

This line was killed in Babel6. Here it was decided:

To always export a default to exports.default

If you are asking about any idea to workaround it?

You can add this line yourself or use some kind of babel plugin that adds it for you.

const myLib = function () {
  console.log('MyLib');
};

export default myLib;

module.exports = myLib;
dreyescat
  • 13,558
  • 5
  • 50
  • 38