8

目前在 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.jsonbaseUrl,因为该目录src/不存在。另外,我注意到该分辨率不适用于模块“util”(它显然是在我的 node_modules 文件夹中使用 util 而不是 node.js util 库),这导致我的应用程序崩溃。

4

1 回答 1

2

根据您提供的来源,您可能可以使用(例如,将最后一个路径解析为第一个路径):

"rootDirs": [
      "src/api/module/path/here",
      "api/module/path/here"
    ]

问题是,我现在需要修改我的 tsconfig.json baseUrl,因为目录 src/ 不存在。

typescript 的路径映射功能指出:

rootDirs 的灵活性不限于指定逻辑合并的物理源目录列表。提供的数组可以包含任意数量的临时、任意目录名称,无论它们是否存在。这允许编译器以类型安全的方式捕获复杂的捆绑和运行时功能,例如条件包含和项目特定的加载器插件。

另外,您是否尝试过跟踪模块分辨率tsc --traceResolution

于 2017-12-29T00:17:02.683 回答