首页 > 解决方案 > 如何通过相对路径导入非 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!");
};

我想使用相对导入来导入ba我已经尝试../../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";

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

这是我的tsconfig.json

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

标签: node.jstypescript

解决方案


推荐阅读