我司由于業(yè)務(wù)調(diào)整需要重新對(duì)現(xiàn)有的web portal 進(jìn)行開(kāi)發(fā).現(xiàn)有的portal 存在10年并且承載了大量業(yè)務(wù),里面有jq,knockout和angularjs 還有react 15和16 簡(jiǎn)直就是一個(gè)前端發(fā)展史有沒(méi)有.
那么這么復(fù)雜的業(yè)務(wù)邏輯的dashboard開(kāi)發(fā)必然要ts
如何初始化一個(gè)npm項(xiàng)目和這里不再細(xì)說(shuō)
在server 下
安裝依賴包
$ npm install --save-dev ts-node nodemon typescript
在之前nodejs 不支持es6語(yǔ)法的時(shí)候,有一個(gè)東西叫babel-node, 就是如果熟悉的人一定知道,就是用來(lái)代替node 命令來(lái)運(yùn)行由es6語(yǔ)法編寫(xiě)而成的nodejs 服務(wù).
基本用法
$ ts-node app.ts
tsconfig.json如下
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"lib": ["es2016", "esnext.asynciterable"],
"outDir": "dist",
"rootDir": "src",
"strict": true,
"esModuleInterop": true,
}
}
大型項(xiàng)目,需要 多人開(kāi)發(fā)的情況下,規(guī)約很重要,那么prettier和eslint 就必須要有..
eslint 配合 prettier 的配置如下 具體的可以在官網(wǎng)去看看相應(yīng)的配置
.prettierrc.js
module.exports = {
semi: true,
trailingComma: "none",
singleQuote: true,
printWidth: 80,
tabWidth: 2
}
接著到.eslintrc.js
parser: '@typescript-eslint/parser',
extends: [
'plugin:@typescript-eslint/recommended',
'prettier/@typescript-eslint',
'plugin:prettier/recommended',
],
parserOptions: {
ecmaVersion: 2016,
sourceType: 'module',
},
rules: {
// Place to specify ESLint rules. Can be used to overwrite rules specified from the extended configs
"@typescript-eslint/explicit-function-return-type": "off",
"@typescript-eslint/interface-name-prefix": "off"
},
};
其實(shí)到這里,基本上
在package.json 的script里添加兩條命令就可以進(jìn)行開(kāi)發(fā)了
"dev": "nodemon --ext js,ts --exec 'npm run lint:dev && ts-node src/main.ts'",
"lint:dev": "eslint './src/**/*.ts'"
ts-node每次不會(huì)產(chǎn)生編譯后的js文件,而是把它們丟到內(nèi)存里, 隨著結(jié)束進(jìn)程就銷毀
因此,eslint 可能不會(huì)起作用對(duì)你的代碼進(jìn)行約束,因此你需要手動(dòng)啟動(dòng) eslint 然后通過(guò)了再 開(kāi)始執(zhí)行ts-node.因?yàn)?nodemon exec參數(shù)傳進(jìn)去的字符串可能有點(diǎn)問(wèn)題,因此,你直接把eslint傳進(jìn)去不工作,所以寫(xiě)成一個(gè)命令即可.
那么大型的項(xiàng)目,需要調(diào)試,那你要設(shè)置斷點(diǎn). vscode設(shè)置斷點(diǎn)這個(gè)玩意真是比較麻煩
打開(kāi)項(xiàng)目,在左邊那個(gè)dubug標(biāo)簽,你點(diǎn)擊它然后會(huì)生成一個(gè)
通過(guò)vscode 的launch.json 去執(zhí)行npm腳本
首先在 package .json中的scripts里加入以下代碼
"debug":"nodemon --ext js,ts --exec node -r ts-node/register --inspect src/main.ts",
解釋一下就是使用nodemon 然后進(jìn)入調(diào)試模式(打好斷點(diǎn)后) 接著執(zhí)行debug模式
ts-node 本身不支持--inspect這個(gè)命令的,所以你需要用用原生的node然后引入ts-node 來(lái)編譯ts -r就是--require的縮寫(xiě)然后開(kāi)始
launch.json如下
{
"version": "0.2.0",
"configurations": [
{
"type": "node2",
"request": "launch",
"name": "Launch Program",
"runtimeExecutable": "npm",
"runtimeArgs": [
"run",
"debug"
],
"cwd": "${workspaceRoot}/server",
"port": 9229,
"console":"intergratedTerminal",
"sourceMaps": true
}
]
}
這樣就萬(wàn)事大吉了,然后你可以直接啟動(dòng),debug會(huì)自動(dòng)監(jiān)聽(tīng)9229 這個(gè)端口,因?yàn)槟?-inspect后,debugger就會(huì)掛載在你的應(yīng)用程序里,通過(guò)websocket來(lái)通信.
然后你就可以愉快地進(jìn)一步搭建基礎(chǔ)設(shè)施啦.