gpt4 book ai didi

javascript - 如何使用 webpack 使用 UMD 模块?

转载 作者:行者123 更新时间:2023-11-30 11:31:55 25 4
gpt4 key购买 nike

在一个普通的 webpack 2 项目中,我正在尝试使用这个 UMD 模块:https://github.com/Offirmo/simple-querystring-parser/blob/master/index.js

没有编译错误。

但是,这最终会在浏览器中出现此错误:

未捕获的类型错误:无法设置未定义的属性“SimpleQuerystringParser”

似乎 webpack 包装提供了 UMD 片段无法识别的环境。

  • 我在 webpack 文档中找不到任何提示
  • 在谷歌上搜索“使用 webpack 使用 UMD”并没有得到有趣的结果
  • StackOverflow 也没有帮助。

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

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

最佳答案

最后,我在 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) {
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://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";

return {
...
}
}))

幸运的是我是库的所有者并且可以修复它。

关于javascript - 如何使用 webpack 使用 UMD 模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45929231/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com