我有以下 typescript :
namespace CompanyName.HtmlTools.Cookie
{
export function eraseCookie(name:string, path:string)
{
createCookie(name, "", path, -1);
}
export function readCookie(name:string)
{
var nameEQ:string = name + "=";
var ca:string[] = document.cookie.split(';');
for(var i=0;i < ca.length;i++)
{
var c:string = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0)
return c.substring(nameEQ.length, c.length);
}
return null;
}
// http://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript
// http://blog.codinghorror.com/protecting-your-cookies-httponly/
export function createCookie(name:string, value:string, path:string, days:number)
{
var expires:string = "";
if(!path)
path = "/";
if (days)
{
var date:Date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "expires=" + date.toUTCString() + "; ";
}
var allValues = name + "=" + encodeURIComponent(value) + "; " + expires + "path=" + path + ";";
if(window.location.protocol === 'https:')
allValues += " secure;"
document.cookie = allValues;
}
export function getDirName(path:string)
{
if(path === null) return '/';
if(path.indexOf("/") !== -1)
{
var subs:string[] = path.split('/') //break the string into an array
subs.pop() //remove its last element
path = subs.join('/') //join the array back into a string
if(path === '')
return '/';
return path;
}
return "/";
}
}
现在我希望能够像这样使用此 typescript 的最小化和优化的 JavaScript:
CompanyName.HtmlTools.Cookie.createCookie("name","value", "path", 2);
但是,当我通过 google closure-compiler 运行它时(仅在高级模式下),漂亮的函数名称消失了,我有 CompanyName.HtmlTools.Cookie.f,这会破坏使用此脚本的所有其他脚本。
现在,问题似乎是,在 TypeScript 转译器创建的未压缩的 javaScript 中,有这样的内容:
Cookie.createCookie = createCookie;
如果是
Cookie["createCookie"] = createCookie;
然后它将在 Closure-Compiler 的高级模式下工作。
有什么方法可以让 TypeScript 将函数导出为
Cookie["createCookie"] = createCookie;
代替
Cookie.createCookie = createCookie;
?
命名空间也一样,应该是
})(window["CompanyName"]|| (window["CompanyName"] = {}));
代替
})(CompanyName || (CompanyName= {}));
最佳答案
使用公共(public)父类(super class)来存储静态方法:
In TypeScript, static properties of classes are inherited, in Closure they are not. To fix this, we create a common superclass.
These fake superclasses don't actually exist and are present solely to simulate the behavior of
goog.inherits(SubClass, SuperClass)
in TypeScript definition files. Callingnew SuperClass__Class
orextends SuperClass__Class
in non-declaration TypeScript code will generate a runtime error. You should usenew SuperClass
andextends SuperClass
in non-declaration TypeScript code.
引用资料
关于javascript - 让 TypeScript 为闭包编译器导出正确的函数名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32697916/