[英]Google closure compiler and UMD pattern
我正在開發一個JavaScript庫,該庫使用閉包編譯器組合/縮小和類型檢查。 為了避免誇大全局命名空間,我想使用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;
}
我已使用output-wrapper-file生成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;
}));
參考: https : //medium.com/reflecting-on-bits/how-to-solve-missing-output-error-when-using-closure-compiler-7de6eac29776? swoff = true# .ntq9vav6s
例
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
編譯器對UMD模式的唯一本地支持是--process_common_js_modules
。 該標志用於將模塊捆綁在一起,並將刪除模式-所以不是您想要的。
您的問題出在輸出包裝器上。 編譯器嘗試通過將其創建為全局this
對象的屬性來導出workspace
。 您的輸出包裝器未指定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));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.