如何通过相对路径导入非TypeScript模块?

时间:2020-07-28 14:05:43

标签: node.js typescript

我具有以下文件结构:

.
├── a
│   ├── package.json
│   ├── src
│   │   └── main.ts
│   └── tsconfig.json
└── b
    ├── package.json
    └── index.js

a是TypeScript模块,b是普通的JavaScript模块。

a / src / main.ts包含以下代码:

import {helloB} from "../../b";
console.log("Hello from A!");
helloB();

b / index.js包含以下代码:

module.exports.helloB = function() {
    console.log("Hello from B!");
};

我想使用相对导入从b导入a。我尝试按照上面指定的方法导入../../b,但是遇到以下错误:

src/main.ts:1:22 - error TS6059: File '/home/ivanq/Documents/tstest/b/index.js' is not under 'rootDir' '/home/ivanq/Documents/tstest/a/src'. 'rootDir' is expected to contain all source files.

1 import {helloB} from "../../b";

我可以将b添加到rootDir,但是我不希望TypeScript编译该模块并将其输出到构建目录。我希望它在运行时执行require("../../b"),就像处理node_modules中的文件一样。如何配置TypeScript来做到这一点?

这是我的tsconfig.json

{
  "compilerOptions": {
    "allowJs": true,
    "outDir": "build",
    "rootDir": "src",
  },
  "include": ["src"]
}

0 个答案:

没有答案
相关问题