在“rootDir”之外导入 Typescript 中的文件

问题描述 投票:0回答:2

我有一个具有以下文件结构的项目

project
|
├── App1/static/App1
|   ├── ts
|   ├── js
|   └── tsconfig.json
|
├── App2/static/App2
|   ├── ts
|   ├── js
|   └── tsconfig.json
|
├── App3/static/App3
|   ├── ts
|   ├── js
|   └── tsconfig.json
|
└── tsconfig.json

每个应用程序都需要在

ts
目录中找到已编译的 Typescript 文件,才能进入同一目录中的每个
js
文件夹。为了使这项工作到目前为止,我在“项目”目录的顶部找到了一个全局
tsconfig.json
文件。然后,在每个应用程序中找到的
tsconfig.json
文件具有以下配置:

{
    "extends": "../../../tsconfig.json",    // Path to global tsconfig.json
    "compilerOptions": {
        "outDir": "js",                     // Where the transpiled Javascript files go
        "rootDir": "ts",                    // Where the Typescript files are
    },
}

然后,例如,当我运行

tsc -p App1/static/App1
时,App1 的
ts
文件夹内的 Typescript 文件将被编译并放置在
js
文件夹内。到目前为止一切都还好。

现在,我的问题是有时 App1 需要 App3 中的文件,所以我进行类似于此的导入:

// App1/static/App1/test.ts
import { module } from "../../../../App3/static/App3/ts/module.js"

这有效,但是,我在导入时收到以下警告:

error TS6059: File 'module.js' is not under 'rootDir' '/ts/'. 'rootDir' is expected to contain all source files.

我可以对 App1 中的

tsconfig.json
文件进行哪些更改才能使其正常工作。我尝试在我的配置中将
../../../App3/static/App3/ts
文件夹添加为
rootDir
(通过使用
rootDirs
),但这似乎不起作用。

typescript tsconfig
2个回答
2
投票

引用package.json文件中的各个子项目

// App1 package.json:
{
    "dependencies": {
        "app2": "../App1/static/App2",
        "app3": "../App1/static/App3",
    }
}

现在您可以将其他应用程序作为外部包引用

import { module } from "app3/js/module.js"

导入已编译的 JavaScript,而不是源打字稿。

我不能 100% 确定您是否需要摆弄导入/导出设置,但这应该可以帮助您完成 90% 的任务。


-1
投票

compilerOptions.rootDir
tsconfig.json
 中移除 
app1

{
    "extends": "../../../tsconfig.json",    // Path to global tsconfig.json
    "compilerOptions": {
        "outDir": "js",                     
    },
}
© www.soinside.com 2019 - 2024. All rights reserved.