Webpack umd library return Object.default

早过忘川 提交于 2019-12-22 12:34:11

问题


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?


回答1:


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;


来源:https://stackoverflow.com/questions/34736771/webpack-umd-library-return-object-default

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!