29

According to the Webpack 4 documentation, if I specify libraryTarget: 'umd' it should result in the following output:

(function webpackUniversalModuleDefinition(root, factory) {
  if(typeof exports === 'object' && typeof module === 'object')
    module.exports = factory();
  else if(typeof define === 'function' && define.amd)
    define([], factory);
  else if(typeof exports === 'object')
    exports["MyLibrary"] = factory();
  else
    root["MyLibrary"] = factory();
})(typeof self !== 'undefined' ? self : this, function() {
  return _entry_return_;
});

However, what I get is:

(function webpackUniversalModuleDefinition(root, factory) {
    if(typeof exports === 'object' && typeof module === 'object')
        module.exports = factory();
    else if(typeof define === 'function' && define.amd)
        define("lib", [], factory);
    else if(typeof exports === 'object')
        exports["lib"] = factory();
    else
        root["lib"] = factory();
})(window, function() {
return

To be more precise, instead of this
(typeof self !== 'undefined' ? self : this, function()
I get this:
(window, function()

This (obviously) causes runtime error window is undefined when importing in node environment.

To be clear:
I know that window doesn't exist in node applications. My question is not about this, but rather about webpack.

Is it a bug or am I missing something?

My output config:

output: {
    path: resolve(__dirname, 'umd'),
    filename: 'lib.js',
    libraryTarget: 'umd',
    library: 'lib',
    umdNamedDefine: true,
},
JeB
  • 11,653
  • 10
  • 58
  • 87
  • What target do you have set: https://webpack.js.org/concepts/targets/ – Jason Aller Mar 05 '18 at 21:47
  • 4
    The default. But it doesn't matter. `libraryTarget: 'umd'` should produce universal code (works both in browser and node). This is according to their documentation: "libraryTarget: "umd" - This exposes your library under all the module definitions, allowing it to work with CommonJS, AMD and as global variable." Also, I built the exact same code with **Webpack 3** and it produced a proper bundle. Bottom line - this is a bug in **Webpack 4** just as I stated in my answer. – JeB Mar 05 '18 at 21:51

2 Answers2

39

This would be a bug in Webpack 4.
Webpack 3 produces a proper bundle.

This issue should be fixed with this feature, until it's done the suggested workaround is using globalObject:

output: {
    path: resolve(__dirname, 'umd'),
    filename: 'lib.js',
    libraryTarget: 'umd',
    library: 'lib',
    umdNamedDefine: true,
    globalObject: `(typeof self !== 'undefined' ? self : this)`
},
JeB
  • 11,653
  • 10
  • 58
  • 87
6

According to the docs include output.globalObject into webpack.config.js:

module.exports = {
  output: {
    libraryTarget: 'umd',
    globalObject: 'this'
  }
}

To make UMD build available on both browsers and Node.js, set output.globalObject option to 'this'.

v.babak
  • 818
  • 11
  • 13