從 JS 到 TS,我們一開始還會用 Webpack 配置來運行我們應用,后面發(fā)現(xiàn)了 ts-node,直接 ts-node index.ts 就可以運行 TS 應用了,不需要用 Webpack 打包成低版本的 JS 才能運行。但是我在用 ts-node 的時候發(fā)現(xiàn)不少坑。
安裝
ts-node 需要在全局去安裝。這里要用 npm 去全局安裝,yarn 全局安裝好像用不了 ts-node。
npm install -g typescript
npm install -g ts-node
當然你 local 安裝也可以的
npm install typescript
npm install ts-node
然后可以使用 npx 去跑 ts-node
npx ts-node index.ts
嘗鮮
我們先來寫一個小項目吧,就輸出 'Hello World'。
const output = 'Hello World'
console.log(output)
夠簡單了吧。運行下面命令可直接跑我們的應用。
ts-node index.ts
成功

tsconfig.json
當我們真正寫項目的時候,是需要 tsconfig.json 來對項目做一些約束的,這里我就用 Vue 自動創(chuàng)建的 tsconfig.json 作為例子。
{
"compilerOptions": {
"target": "es2018",
"module": "commonjs",
"moduleResolution": "node",
"lib": [
"esnext",
"esnext.asynciterable",
"dom"
],
"esModuleInterop": true,
"allowJs": true,
"sourceMap": true,
"strict": true,
"noEmit": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"baseUrl": ".",
"skipLibCheck": true,
"paths": {
"@/*": [
"./*"
]
},
"types": [
"@types",
"jest"
]
},
"include": [
"index.ts",
"lib.ts"
],
"exclude": [
"node_modules",
"dist"
]
}
使用 tsconfig.json
定義好 tsconfig.json 后,我們要測試一下是否真的能夠使用了。我們先新創(chuàng)建另個文件 lib.ts
export const add = (a: number, b: number) => {
return a + b
}
這里面就定義一個加法函數(shù),然后在 index.ts 去運行一下。
import {add} from '@/lib'
const output = 'Hello World'
console.log(output)
console.log(add(1, 2))
但是報錯:Error: Cannot find module '@/lib'。

在 tsconfig.json 里定義的 @ 別名,ts-node 根本不鳥你。所以我們懷疑 ts-node 沒有識別 tsconfig.json。查了一圈發(fā)現(xiàn)這個 https://stackoverflow.com/questions/51610583/ts-node-ignores-d-ts-files-while-tsc-successfully-compiles-the-project。ts-node 7.0.0 以上就不自動識別 tsconfig.json 了,得加上 --files 才能識別,好吧。
ts-node index.ts --files
結果還是

真正使用你的別名
按照 stackoverflow 上的提示肯定是可以識別 tsconfig.json 的,所以這里我的猜想是 ts-node 不支持alias,畢竟這玩竟其實屬于 webpack。查了一下,果然。
https://github.com/TypeStrong/ts-node/issues/138 這個 Issue 就說明了我們剛剛遇到了不能使用 alias 的問題。解決方案是我們得再裝一個 tsconfig-paths 的包。沒辦法.
yarn add -D tsconfig-paths
再改改他給的命令:
ts-node -r tsconfig-paths/register index.ts --files
總算是成功了。

總結
- 使用 ts-node 的時候要添加
--files去識別你的 tsconfig.json 文件 - 安裝
tsconfig-paths這個包來使用路徑別名 alias
這兩個點雖然很簡單,上面的例子就輸出和做個加法,但是在我做項目的時候是花很大力氣去排查的,所以大家一定不要怕麻煩,可能解決方法就是這么的簡單。