简体   繁体   English

Webpack umd 库返回 Object.default

[英]Webpack umd library return Object.default

I'm writing a lib with webpack with these settings:我正在使用这些设置使用 webpack 编写一个库:

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...问题是,当我尝试在浏览器中加载 build/my_lib.js 时,访问 MyLib 的唯一方法是通过 MyLib.default ...

Any idea?任何的想法?

You should set libraryExport to default ;您应该将libraryExport设置为default

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

the key is to use libraryExport: "default" like this:关键是像这样使用libraryExport: "default"

  module.exports = {
    entry: ...,
    output: {
      path: __dirname + "/dist/",
      filename: "Template.js",
      library: "Template",
      libraryTarget: "umd",
      libraryExport: "default",
      globalObject: "this",
    },

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.如果您使用 Babel 启用 ES6 功能,那么您可能面临 Babel5 和 Babel6 之间的变化之一。

With Babel5 your code is transpiled to this:使用 Babel5,您的代码将被转换为:

'use strict';

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

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

module.exports = exports['default'];

But with Babel6 you get:但是使用 Babel6 你会得到:

'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.这条线在 Babel6 中被杀死了。 Here it was decided:在这里决定:

To always export a default to exports.default始终将默认值导出到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 .您可以自己添加此行或使用某种babel 插件为您添加它

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

export default myLib;

module.exports = myLib;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM