在koa+ts项目中,配置tsconfig使其IDE支持快速跳转,可是用tsnode编译时报错node
代码以下webpack
import {add} from '@/lib'
const output = 'Hello World'
console.log(output)
console.log(add(1, 2))
复制代码
可是编译时报错:Error: Cannot find module '@/lib'。
git
在 tsconfig.json 里定义的 @ 别名,ts-node 根本不鸟你。因此咱们怀疑 ts-node 没有识别 tsconfig.json。查了一圈发现这个 stackoverflow.com/questions/5…github
ts-node 7.0.0 以上就不自动识别 tsconfig.json 了,得加上 --files
才能识别,好吧。web
运行 ts-node ./src/main.ts --files
npm
结果仍是报错json
按照 stackoverflow 上的提示确定是能够识别 tsconfig.json 的,因此这里个人猜测是 ts-node 不支持alias,毕竟这玩竟其实属于 webpack。查了一下,果真。markdown
github.com/TypeStrong/… 这个 Issue 就说明了咱们刚刚遇到了不能使用 alias 的问题。解决方案是咱们得再装一个 tsconfig-paths 的包。app
npm i -D tsconfig-paths
ts-node -r tsconfig-paths/register ./src/main.ts --files
复制代码
总算是成功了。koa
参考:www.barretlee.com/blog/2019/0…
// launch.json配置
"runtimeExecutable": "/usr/local/bin/nodemon",
"runtimeArgs": [
"--exec",
"ts-node",
"-r",
"tsconfig-paths/register",
"--files"
],
"program": "${workspaceFolder}/src/main.ts",
复制代码
以上配置至关于执行了
[nodemon] starting `ts-node -r tsconfig-paths/register --files ./src/main.ts`
复制代码
// launch.json配置
"runtimeExecutable": "/usr/local/bin/nodemon",
"runtimeArgs": [
"--exec",
"ts-node",
"-r",
"tsconfig-paths/register",
"--files"
],
"args": ["${workspaceFolder}/src/main.ts"],
复制代码
以上配置至关于执行了
[nodemon] starting `ts-node -r tsconfig-paths/register --files /Users/xxx/xxx/src/main.ts`
复制代码
能够看到,地址变成了绝对路径
使用 ts-node 的时候要添加 --files 去识别你的 tsconfig.json 文件
安装 tsconfig-paths 这个包来使用路径别名 alias