我在我的库中有一个可选的依赖项,我想通过UMD / AMD标头导入,就像:
(function(root, factory) {
if (typeof exports === "object") {
module.exports = factory(require('proj4'));
} else if (typeof define === "function" && define.amd) {
define(['proj4'], factory);
} else {
root.ol = factory(root.proj4);
}
}(this, function(proj4) {
...
// proj4 is an "optional" dependency, just like a plugin
if('function' === typeof proj4){
// use proj4 within here
}
});
上面这个定义的问题是,当proj4
不可用时,这将无效,这是一个完全有效的案例。我觉得我在这里遗漏了一些明显的东西......有没有关于如何处理这种情况的“标准”解决方案?
我的意思是......我想我能做的就是......
(function(root, factory) {
if (typeof exports === "object") {
module.exports = factory();
} else if (typeof define === "function" && define.amd) {
define([], factory);
} else {
root.ol = factory();
}
}(this, function() {
var proj4 = null;
try {
proj4 = require('proj4');
} catch(e) {
// loading failed
}
...
// proj4 is an "optional" dependency, just like a plugin
if('function' === typeof proj4){
// use proj4 within here
}
});
这是要遵循的路径还是有更好的解决方案?
THX