2017-08-29 71 views
0

在一个简单的webpack 2项目中,我试图使用这个UMD模块:https://github.com/Offirmo/simple-querystring-parser/blob/master/index.js如何使用webpack消费UMD模块?

没有转译错误。

然而,这结束了这个错误在浏览器:

Uncaught TypeError: Cannot set property 'SimpleQuerystringParser' of undefined

看来的WebPack包裹被提供了UMD片段无法识别的环境。

  • 我coulndn't找到“消费与UMD的WebPack”中的WebPack DOC
  • 任何暗示谷歌搜索没有拿出有趣的结果
  • StackOverflow上是无益无论是。

那么如何在webpack中使用我的UMD库呢?

注意:是的,目标UMD库是我的,但它使用UMD官方网站的合法UMD片段。欢迎任何建议。

+0

这里接受的答案_might_对你有帮助。 https://stackoverflow.com/questions/14150203/is-it-possible-to-convert-requirejs-modules-to-commonjs - 祝你好运! – iamjpg

+1

@iamjpg谢谢,但不是真的我在找什么。 UMD是合法的,我希望webpack能够在不改变的情况下使用它(尽管我最终适应了webpack,比较了我的答案......) – Offirmo

回答

2

最后,我debbuged的WebPack 2环境下的UMD包装,并能拿出一个改进 UMD的包装也可以工作在的WebPack 2:(可在一个要点这里https://gist.github.com/Offirmo/ec5c7ec9c44377c202f9f8abcacf1061#file-umd-js

// Iterating on the UMD template from here: 
 
// https://github.com/umdjs/umd/blob/master/templates/returnExportsGlobal.js 
 
// But experimentally improving it so that it works for webpack 2 
 

 
// UMD template from https://gist.github.com/Offirmo/ec5c7ec9c44377c202f9f8abcacf1061#file-umd-js 
 
(function (root, factory) { 
 
    \t var LIB_NAME = 'Foo' 
 
\t if (typeof define === 'function' && define.amd) { 
 
\t \t // AMD. Register as an anonymous module. 
 
\t \t define(function() { 
 
\t \t \t return (root 
 
\t \t \t \t ? root[LIB_NAME] = factory() 
 
\t \t \t \t : factory() // root is not defined in webpack 2, but this works 
 
\t \t \t) 
 
\t \t }); 
 
\t } else if (typeof module === 'object' && module.exports) { 
 
\t \t // Node. Does not work with strict CommonJS, but 
 
\t \t // only CommonJS-like environments that support module.exports, 
 
\t \t // like Node. 
 
\t \t module.exports = factory() 
 
\t } else if (root) { 
 
\t \t // Browser globals 
 
\t \t root[LIB_NAME] = factory() 
 
\t } else { 
 
\t \t throw new Error('From UMD wrapper of lib "' + LIB_NAME + '": unexpected env, cannot expose my content!') 
 
\t } 
 
}(this, function() { 
 
\t "use strict"; 
 
    
 
    \t return { 
 
\t \t ... 
 
\t } 
 
}))

的信息,原包装,不在的WebPack 2个工作:(从这里https://github.com/umdjs/umd/blob/master/templates/returnExportsGlobal.js

(function (root, factory) { 
 
    if (typeof define === 'function' && define.amd) { 
 
     // AMD. Register as an anonymous module. 
 
     define(function() { 
 
      return (root.returnExportsGlobal = factory()); 
 
     }); 
 
    } else if (typeof module === 'object' && module.exports) { 
 
     // Node. Does not work with strict CommonJS, but 
 
     // only CommonJS-like environments that support module.exports, 
 
     // like Node. 
 
     module.exports = factory(); 
 
    } else { 
 
     // Browser globals 
 
     root.returnExportsGlobal = factory(); 
 
    } 
 
}(this, function() { 
 
    "use strict"; 
 
    
 
    \t return { 
 
\t \t ... 
 
\t } 
 
}))

幸运的是我的lib的所有者,并可以修复它。