如何从nodejs typescript包的子目录导入?

mklgxw1f  于 2022-12-03  发布在  Node.js
关注(0)|答案(1)|浏览(165)

让我们假设一个包含以下文件的npm包:

./index.ts
./controller/index.ts
./controller/my-controller.ts

tsconfig.json:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "declaration": true,
    "outDir": "./lib",
    "strict": true,
  },
  "include": ["src"],
  "exclude": ["node_modules", "**/__tests__/*"],
  "paths": {
      "my-package": ["./src/index"],
      "my-package/controller": ["./src/controller/index"]
  }
}

控制器中的index.ts文件正在导出my-controller。我现在要做的是导入MyController,如下所示:
import {MyController} from 'my-package/controller';
但我得到的信息是:Cannot find module 'my-package/controller' or its corresponding type declarations.。从根目录中的./index.ts导入可以正常工作。

xytpbqjk

xytpbqjk1#

在这个https://github.com/microsoft/TypeScript/issues/33079的最后一个注解中,提到了在tsconfig.json中将“moduleResolution”更改为“Node16”。更改后,它对我来说工作得很好。

相关问题