【问题标题】:How to consume an UMD module with webpack?如何使用 webpack 使用 UMD 模块?
【发布时间】:2017-08-29 01:00:23
【问题描述】:

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

没有转译错误。

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

Uncaught TypeError: Cannot set property 'SimpleQuerystringParser' of undefined

似乎 webpack 包装提供了一个 UMD sn-p 无法识别的环境。

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

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

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

【问题讨论】:

  • 此处接受的答案可能对您有所帮助。 stackoverflow.com/questions/14150203/… - 祝你好运!
  • @iamjpg 谢谢,但不是我真正想要的。 UMD 是合法的,我希望 webpack 能够在不改变的情况下使用它(尽管我最终适应了 webpack,参见我的回答......)

标签: javascript webpack umd


【解决方案1】:

最后,我在 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 {
		...
	}
}))

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

【讨论】:

    猜你喜欢
    • 2021-09-17
    • 2018-06-15
    • 1970-01-01
    • 1970-01-01
    • 2019-10-24
    • 1970-01-01
    • 2018-11-28
    • 2017-05-12
    • 2018-07-06
    相关资源
    最近更新 更多