[英]Webpack output UMD library with CamelCase and spinal-case name
如何配置Webpack来创建UMD捆绑包,以便AMD和CommonJS的包名称将以小写字母(小写字母)命名,而全局上下文的名称将为CamelCase名称?
例如,我希望我的捆绑包以
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("dependency"));
else if(typeof define === 'function' && define.amd)
define("my-library", ["dependency"], factory); // spinal-case
else if(typeof exports === 'object')
exports["my-library"] = factory(require("dependency")); // spinal-case
else
root["MyLibrary"] = factory(root["dependency"]); // CamelCase
})...
这是在ReactDOM中的样子:
(function(f) {
// CommonJS
if (typeof exports === "object" && typeof module !== "undefined") {
module.exports = f(require('react'));
// RequireJS
} else if (typeof define === "function" && define.amd) {
define(['react'], f);
// <script>
} else {
var g;
if (typeof window !== "undefined") {
g = window;
} else if (typeof global !== "undefined") {
g = global;
} else if (typeof self !== "undefined") {
g = self;
} else {
// works providing we're not in "use strict";
// needed for Java 8 Nashorn
// see https://github.com/facebook/react/issues/3037
g = this;
}
g.ReactDOM = f(g.React);
}
})(function(React)...
您还应该将umdNamedDefine
属性设置为true
。 这是我做UMD包装的库时通常的output
块。 我将使用当前拥有的一个npm包中的示例,因为这将是最说明性的:
output: {
path: './lib',
filename: 'dom-regex.js',
library: 'DomRegex',
libraryTarget: 'umd',
umdNamedDefine: true
},
鉴于我的npm软件包在package.json
名为dom-regex
,这使我可以通过以下方式使用我的软件包:
ES6:
import DomRegex from 'dom-regex';
需求JS
var DomRegex = require('dom-regex');
在窗口上:(如果文件直接显示在窗口上)
window.DomRegex
在UMD包装部分中导出的名称并不像在导入时命名的名称那么重要。 以dom-regex
为例,即使我在项目本地(而不是在node_modules中),并且文件名是dom-regex.js
,我仍然可以做所有前面的示例,因为它是UMD包装的:
欢迎您浏览dom-regex的仓库,并测试下载该软件包以了解其工作原理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.