解决ts-node tsconfig 配置 path 后,相对路径找不到的问题
由于配置了
tsconfig.json
中的path
字段,设置如下:
"paths": { "*": [ "node_modules/*", "src/types/*", "src/*" ] },
配置
path
可以让我在引入其他文件的时候,不需要从src
开始
//未使用的情况下,需要这样引入 import { render, saveFile } from '../core/render' // 配置 path 字段后,可以这样引入,默认指向 src目录下 import { render, saveFile } from 'core/render'
使用 tsconfig-paths
解决 ts-node 不识别路径问题
ts-node 不能够加载 tsconfig
导致无法解析这种相对路径的引用,下面是具体解释为什么为找不到路径
Typescript by default mimics the Node.js runtime resolution strategy of modules. But it also allows the use of path mapping which allows arbitrary module paths (that doesn’t start with “/” or “.”) to be specified and mapped to physical paths in the filesystem. The typescript compiler can resolve these paths from
tsconfig
so it will compile OK. But if you then try to execute the compiled files with node (or ts-node), it will only look in thenode_modules
folders all the way up to the root of the filesystem and thus will not find the modules specified bypaths
intsconfig
.
具体做法
因为我使用 nodemon
所以在使用 ts-node
时候,这样写:
"execMap": {
"ts": "ts-node -r tsconfig-paths/register"
},
配置完成重新启动项目解决!