背景
用js寫了幾年前端程序,一直用extjs框架,最近學習了下angular覺得技術有必要升級換代了,於是就從把mxGraph從javascript轉換爲typescript開始了,本文介紹一下轉換中常見問題。
轉換步驟
1. 將*.js文件重命名爲*ts文件;
2. 在vscode中逐個修改ts文件中的js代碼:
2.1 將var 替換爲 const /let ;
2.2 用class{ constructor() ... } 進行對象化封裝;
2.3 消滅95%的prototype;
2.4 import依賴的外部類,vscode有一次全部import的功能;
2.4 一部分提示錯誤的window替換爲globalThis;
2.5 用箭頭函數=>替代大部分函數綁定;
2.6 對屬性、函數參數和返回值進行類型標註;
2.7 用angular ng build/ ng serve進行編譯和測試;
2.8 重新劃分類及類所在文件以便消除循環引用(a import b,b import a);
2.9 對代碼進行局部的重構和優化。
典型問題
1.消除prototype
在mxGraph中採用了prototype實現對象化,在typescript和es6中提供了class+constructor的對象化方式,兩者之間的轉換就是消除prototype的過程。
先將 “function 類名” 修改了 “class 類名{”,去掉 屬性 前面的“類名.prototype.”,去掉方法前的 "類名.prototype." 和後面的"=function。修改前的js代碼:
function mxCell(value, geometry, style)
{
this.value = value;
this.setGeometry(geometry);
this.setStyle(style);
if (this.onInit != null)
{
this.onInit();
}
};
mxCell.prototype.id = null;
mxCell.prototype.getId = function()
{
return this.id;
};
修改後的ts代碼:
export class mxCell {
id = null;
constructor(value?, geometry?: mxGeometry, style?: string) {
this.value = value;
this.setGeometry(geometry);
this.setStyle(style);
if (this.onInit != null) {
this.onInit();
}
}
getId() {
return this.id;
}
}
對於在其他文件中對“類名.prototype.方法”修改的部分,能夠合併的合併到mxCell類,不能合併的通過增加子類來實現。
對於在其他文件中對“類名.prototype.屬性"的訪問,類型化中可以定義兩個同名屬性,其中一個爲static,然後將“類名.prototype.屬性"訪問替換爲“類名.屬性"。
由於prototype對象化存在原型鏈污染問題,使得js代碼難以分析和調試,儘量避免使用。
2.箭頭函數的使用
js中函數通過綁定來保持函數內的this指向編譯時的調用者,並傳遞arguments,箭頭函數=>很適合用來替換這種綁定,但由於箭頭函數不能傳遞arguments,因此在遇到函數內出現apply(this, arguments)時要將arguments替換爲參數數組。對於綁定給非this對象,不適合用箭頭函數。
this.resetHandler = mxUtils.bind(this, function()
{
if (this.toolbar != null)
{
this.toolbar.resetMode(true);
}
});
//修改爲
this.resetHandler = ()=>
{
if (this.toolbar != null)
{
this.toolbar.resetMode(true);
}
});
3.ts中調用第三方js庫
首先,需要在tsconfig.json中包含js文件
"include": [
"src/assets/base64.js",
"src/assets/pako.min.js",
"src/assets/sanitizer.min.js",
"src/assets/jscolor/jscolor.js"
]
然後在使用庫的ts文件中聲明js對象declare const jscolor; 之後jscolor就可以調用了。
效果
1. 代碼重構後更加規範、易讀,對象化代碼更易於擴展;
2. 強類型後vscode幫助發現了很多編譯錯誤;
3. 代碼瘦身。