我正在开发一个javascript库,它使用闭包编译器来组合/缩小&类型检测。为了避免pouting全局命名空间,我想使用UMD模式&关闭@export(or goog.exportSymbol('workspace', lkr.workspace)
goog.provide('workspace');
goog.require('lkr.workspace');
/**
* Exposed external access point
* @export
* @return {component}
*/
workspace = function() {
return lkr.workspace.Core;
}
我使用了输出包装器文件来生成UMD包装器
//UMD bundling closure code inside.
;(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define([], factory);
} else if (typeof module === 'object' && module.exports) {
module.exports = factory();
} else {
root.workspace = factory();
}
}(this, function () {
%output%
return workspace;
}));
示例
start.js
goog.provide('workspace');
/**
* Exposed external access point
* @export
* @return {number}
*/
var workspace = function() {
console.log('My workspace')
return 0;
}
编译标志
closure_entry_point: 'workspace',
compilation_level: ADVANCED_OPTIMIZATION,
only_closure_dependencies: true,
generate_exports :true,
language_in : 'ECMASCRIPT5_STRICT',
language_out : 'ES5_STRICT',
使用UMD包装器输出
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
define([], factory);
} else if (typeof exports === 'object') {
module.exports = factory();
} else {
root.workspace = factory();
}
}(this, function() {
'use strict';
'use strict';
function a() {
console.log("My workspace");
return 0
}
var b = ["workspace"]
, c = this;
b[0]in c || !c.execScript || c.execScript("var " + b[0]);
for (var d; b.length && (d = b.shift()); )
b.length || void 0 === a ? c[d] ? c = c[d] : c = c[d] = {} : c[d] = a;
return workspace;
}));
错误:
Uncaught TypeError: Cannot use 'in' operator to search for 'workspace' in undefined
Uncaught ReferenceError: workspace is not defined
答案 0 :(得分:2)
编译器对UMD模式的唯一本机支持是--process_common_js_modules
。该标志用于将模块捆绑在一起,并将删除模式 - 所以不是你想要的。
您的问题与输出包装有关。编译器尝试通过将其创建为全局workspace
对象上的属性来导出this
。您的输出包装器未指定this
对象。由于您处于严格模式,因此它也不会自动强制转换为全局this
对象。
将输出包装器更新为:
//UMD bundling closure code inside.
;(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define([], factory);
} else if (typeof module === 'object' && module.exports) {
module.exports = factory();
} else {
root.workspace = factory();
}
}(this, function () {
%output%
return workspace;
}.bind(this));