【问题标题】:Issue with typescript path resolution. (Error: Cannot find module '[module_name]')打字稿路径解析问题。 (错误:找不到模块'[module_name]')
【发布时间】:2022-01-25 23:56:58
【问题描述】:

我有一个带有打字稿的节点项目设置。一切都很好,但最近我一直想实现路径解析。 为什么这么麻烦?

这是我的项目架构:

└───src
    ├───models
    ├──────Person.ts
    ├───query
    ├──────index.ts
    └───index.ts
├───package.json
└───tsconfig.json

我的 tsconfig 设置如下:

{
  "compilerOptions": {
    "moduleResolution": "node",
    "rootDir": "./src",
    "outDir": "./build",
    "baseUrl": "./src",
    "paths": {
      "@models/*": [ "models/*" ]
    }
  },
  "exclude": [ "node_modules", "build" ],
  "include": [ "src/**/*.ts" ],
}

在 VS 代码中一切正常。
我可以使用以下方法轻松地从我的索引文件中导入 Person.ts:

import Person from '@models/Person'.

tsc 构建时没有任何错误或警告。

但是当我跑步时

node build/index.js

它给了我以下错误:

Error: Cannot find module '@models/Person'

打字稿编译后路径似乎没有正确转换。

有什么想法吗?

【问题讨论】:

    标签: typescript typescript-module-resolution


    【解决方案1】:

    这是我最终寻求的解决方案:
    我已将cross-envtsconfig-path 添加到我的package.json
    允许我这样运行我的项目:

    "scripts": {
      "start": "cross-env TS_NODE_BASEURL=./build node --require tsconfig-paths/register ./build/index.js",
      "build": "tsc",
      "watch": "tsc-watch --onSuccess \"yarn start\""
    },
    

    请注意,我使用 cross-env 包只是因为我在 Windows 上。

    我仍然不明白为什么路径解析不是打字稿编译所固有的,但无论如何。它就像一个魅力!在 Linux 和 Windows 上

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-28
      • 2018-07-30
      • 2021-06-28
      • 1970-01-01
      • 2018-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多