使用 Google Closure 定义配置对象的最佳方法
我喜欢 Google Closure 编译器如何优化代码中的符号。但是,我还没有找到一种好方法来定义将配置对象作为参数的公共导出函数。考虑以下代码片段:
goog.provide('foo');
goog.require('goog.dom');
/** @typedef {{
* id : string,
* clazz : string
* }}
*/
foo.config;
/**
* Does some neat stuff
* @param {foo.config} config
*/
foo.myFoo = function(config) {
var el = goog.dom.getElement(config.id);
goog.dom.classes.add(el, config.clazz);
}
goog.exportSymbol('foo.myFoo', foo.myFoo);
现在假设我们加载此脚本,并希望按如下方式调用 myFoo:
<script type="text/javascript">
foo.myFoo({
id: 'unique-id',
clazz: 'pretty'
});
</script>
如果编译,这将失败,因为 id 和 clazz 属性被压缩。
有谁知道使用 Google Closure 编译器实现和导出配置对象的优雅方法?
I love how Google Closure compiler will optimize symbols in code. However, I have not found a good way to define public, exported functions that take configuration objects as parameters. Consider this code snippet:
goog.provide('foo');
goog.require('goog.dom');
/** @typedef {{
* id : string,
* clazz : string
* }}
*/
foo.config;
/**
* Does some neat stuff
* @param {foo.config} config
*/
foo.myFoo = function(config) {
var el = goog.dom.getElement(config.id);
goog.dom.classes.add(el, config.clazz);
}
goog.exportSymbol('foo.myFoo', foo.myFoo);
Now assume we load this script, and want to call myFoo as follows:
<script type="text/javascript">
foo.myFoo({
id: 'unique-id',
clazz: 'pretty'
});
</script>
If compiled, this would fail because id and clazz properties were compressed.
Does anyone know of an elegant way to implement and export configuration objects using the Google Closure compiler?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我的建议是简单地将参数注释为
{Object}
并引用键,如下所示:My suggestion would be to simply annotate the parameter as
{Object}
and quote the keys, as below:关于损坏的属性名称和原始属性名称的冲突
您必须执行以下任一操作:
关于配置对象
根据 Closure Compiler 文档,目前你还不能这样做。您必须将参数标记为对象。
您可以定义一个类型,但这对您没有帮助,因为类型需要所有属性都存在,但您只能在配置对象中设置几个参数。
Closure Compiler 文档建议您将参数标记为对象,但在注释中记录字段。
Regarding conflicts of mangled and raw property names
You'll have to either:
Regarding configuration objects
According to the Closure Compiler docs, currently you can't do it. You have to mark the param as Object.
You may define a type, but it won't help you because a type requires all the properties to exist, but you may only set a few parameters in a configuration object.
The Closure Compiler documentation recommends that you mark the parameter as Object, but document the fields in comments.