2017-08-29 142 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的所有者,並可以修復它。