Webpack umd library return Object.default
Asked Answered
A

3

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?

Abate answered 12/1, 2016 at 6:17 Comment(0)
H
18

You should set libraryExport to default;

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

Hatteras answered 30/12, 2019 at 9:45 Comment(0)
F
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",
    },
Finnegan answered 25/12, 2020 at 22:29 Comment(0)
B
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;
Brainbrainard answered 13/1, 2016 at 22:36 Comment(1)
Please consider voting for feature request here: github.com/webpack/webpack/issues/3929 ;)Styracaceous

© 2022 - 2024 — McMap. All rights reserved.