‘api / *’应该在根文件夹中查找.在开发工作中使用以下内容:
nodemon --watch src -e ts,tsx --exec ts-node -r tsconfig-paths/register --disableWarnings ./src/index.ts
tsconfig-paths / register允许正确转换需求,ts-node将正确执行/运行应用程序.现在,当我转向生产时,问题就出现了.在过去的制作中,我只是在文件夹上运行tsc,并将outDir(dist /)的内容移动到我的docker镜像中的/ app,然后运行node /app/index.js.这一直有效,直到我开始使用typescript的路径映射功能.现在我只是得到错误:
Error: Cannot find module ‘api/module/path/here’
从this github comment开始,模块名称显然没有映射到输出编译的javascript.
我的tsconfig.json文件:
{ "compilerOptions": { "target": "es2015","module": "commonjs","moduleResolution": "node","allowSyntheticDefaultImports": true,"jsx": "react","allowJs": true,"alwaysStrict": true,"sourceMap": true,"forceConsistentCasingInFileNames": true,"noFallthroughCasesInSwitch": true,"noImplicitReturns": true,"noUnusedLocals": true,"noUnusedParameters": true,"noImplicitAny": false,"noImplicitThis": false,"strictNullChecks": false,"experimentalDecorators": true,"emitDecoratorMetadata": true,"lib": ["es2017","dom"],"baseUrl": "src","outDir": "dist","types": [ "node" ],"paths": { "universal/*": ["../../universal/*"],"api/*": ["*"],"*": ["node_modules/*"] },"typeRoots": [ "./node_modules/@types","./src/types" ] },"include": [ "src/**/*" ] }
在node.js环境中使用相对路径映射的推荐方法是什么?如果打字稿是执行解决方案的那个,为什么不重写require语句呢?让babel或webpack这样的另一个步骤只是为了添加打字稿提供模块分辨率的功能感觉很愚蠢.
编辑:经过额外的挖掘,我发现我可以在我的节点环境中使用-r tsconfig-paths / register(我只需要在我的tsconfig.json文件中复制).我可以将docker中的入口点切换为:
ENTRYPOINT [ "node","-r","tsconfig-paths/register","index.js" ]
问题是,我现在需要修改我的tsconfig.json baseUrl,因为目录src /不存在.另外,我注意到解决方案不适用于模块’util'(它显然在我的node_modules文件夹中使用util而不是node.js util库),这导致我的应用程序崩溃.
解决方法
"rootDirs": [ "src/api/module/path/here","api/module/path/here" ]
The problem is,I now need to modify my tsconfig.json baseUrl,as the
directory src/ doesn’t exist.
typescript’s path mapping feature州:
The flexibility of rootDirs is not limited to specifying a list of physical source directories that are logically merged. The supplied array may include any number of ad hoc,arbitrary directory names,regardless of whether they exist or not. This allows the compiler to capture sophisticated bundling and runtime features such as conditional inclusion and project specific loader plugins in a type safe way.
此外,您是否尝试了跟踪模块分辨率:tsc –traceResolution