目前在 node.js 应用程序中使用 typescript。我已经编译了我的应用程序,并且正在使用typescript 的路径映射功能。
'api/*' 应该在根文件夹中查找。在开发工作中使用以下内容:
nodemon --watch src -e ts,tsx --exec ts-node -r tsconfig-paths/register --disableWarnings ./src/index.ts
tsconfig-paths/register
允许正确翻译 require 并且 ts-node 将正确执行/运行应用程序。现在,当我开始生产时,问题就出现了。过去在生产中,我只是简单地tsc
在文件夹上运行,并将 outDir (dist/) 的内容移动到我的 docker 映像中的 /app 中,然后运行node /app/index.js
. 这一直有效,直到我开始使用 typescript 的路径映射功能。现在我只是得到错误:
错误:找不到模块 'api/module/path/here'
从这个 github 评论中,模块名称显然没有映射到输出编译的 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 这样的另一个步骤只是为了添加 typescript 通过模块解析提供的功能感觉很愚蠢。
编辑:经过额外的挖掘,我发现我可以-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 库),这导致我的应用程序崩溃。