UMD实现范例
(function (root, factory) {
if (typeof module === 'object' && typeof module.exports === 'object') {
console.log('是commonjs模块规范,nodejs环境');
var depModule = require('./umd-module-depended');
module.exports = factory(depModule);
} else if (typeof define === 'function' && define.amd) {
console.log('是AMD模块规范,如require.js');
define(['depModule'], factory);
} else if (typeof define === 'function' && define.cmd) {
console.log('是CMD模块规范,如sea.js');
define(function (require, exports, module) {
var depModule = require('depModule');
module.exports = factory(depModule);
});
} else {
console.log('没有模块环境,直接挂载在全局对象上');
root.umdModule = factory(root.depModule);
}
})(this, function (depModule) {
console.log('我调用了依赖模块', depModule);
// ...省略了一些代码,去代码仓库看吧
function add(a, b) {
return a + b;
}
return {
name: '我自己是一个umd模块',
add: add,
};
});
在html中引用范例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>测试</title>
<script src="./test.js"></script>
<script>
console.log(window.umdModule.name);
const result = window.umdModule.add(2, 3);
console.log('resu:', result);
</script>
</body>
</html>
控制台结果