在一个简单的webpack 2项目中,我尝试使用此UMD模块:https://github.com/Offirmo/simple-querystring-parser/blob/master/index.js
没有转换错误。
但是,这最终会在浏览器中出现此错误:
Uncaught TypeError: Cannot set property 'SimpleQuerystringParser' of undefined
似乎webpack包装正在提供UMD片段无法识别的环境。
那么如何在webpack中使用我的UMD库呢?
注意:是的,目标UMD库是我的,但它使用来自官方UMD网站的合法UMD片段。欢迎任何建议。
答案 0 :(得分:3)
最后,我在webpack 2环境下重新编写了UMD包装器,并且能够提出一个改进的 UMD包装器,它也适用于webpack 2 :(可在此处使用{{3 }})
// 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) {
var LIB_NAME = 'Foo'
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(function () {
return (root
? root[LIB_NAME] = factory()
: factory() // root is not defined in webpack 2, but this works
)
});
} 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 if (root) {
// Browser globals
root[LIB_NAME] = factory()
} else {
throw new Error('From UMD wrapper of lib "' + LIB_NAME + '": unexpected env, cannot expose my content!')
}
}(this, function () {
"use strict";
return {
...
}
}))

有关信息,webpack 2中的原始包装无法正常工作 :(来自此处https://gist.github.com/Offirmo/ec5c7ec9c44377c202f9f8abcacf1061#file-umd-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";
return {
...
}
}))

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