【发布时间】:2021-09-14 21:07:35
【问题描述】:
抱歉,这里的标题含糊不清,这是我不知道自己不知道的问题之一。让我描述一下我的目录结构:
root
src
tsconfig.json
test
tsconfig.json
tsconfig.json
这是一些遗留代码。通常我喜欢设置我的项目,以便测试文件和源文件在同一个目录中,但这将是一个巨大的变化,所以我试图弄清楚如何让它以它已经结构化的方式工作。
基本上,我希望能够在测试文件中执行此操作:
// current file: test/downloader_test.ts
// downloader file: src/downloader.ts
import { Downloader } from "./downloader";
...
当源文件和测试文件位于同一目录中时,我可以执行此操作,但在这种情况下,它们位于不同的目录中,因此我在导入行中收到有关“./downloader”不存在的错误。
有一个已经在使用的解决方法:相反,我可以从../lib/downloader 导入,它可以工作,但我希望能够参考打字稿文件。 测试文件在单独的 tsconfig.json 文件下时,有什么方法可以导入 typescript 源文件?
我认为如果存在解决方案,它可能是 tsconfig 设置。这些是我目前的样子:
根/tsconfig.json:
{
"compilerOptions": {
"rootDir": ".",
},
"files": [],
"references": [
{
"path": "./src"
},
{
"path": "./test"
},
]
}
root/src/tsconfig.json:
{
"compilerOptions": {
"module": "commonjs",
"outDir": "../lib",
"noImplicitReturns": true,
"noUnusedLocals": true,
"sourceMap": true,
"strict": true,
"lib": ["es2020", "dom"],
"target": "es2019",
"composite": true,
"allowSyntheticDefaultImports": true
},
"compileOnSave": true,
"types": ["node"],
"include": ["**/*.ts"]
}
root/test/tsconfig.json:
{
"compilerOptions": {
"module": "commonjs",
"outDir": "../libtest",
"strict": false,
"composite": true,
"sourceMap": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true
},
"include": [
"**/*.ts"
]
}
我也尝试修改最后一个文件以添加一个
"references": [
{
"path": "../src"
}
]
但这对我来说没有任何改变。
【问题讨论】:
-
您可以更改 test/tsconfig.json 的配置,以便它也可以从 src/ 目录中转译文件,但如果您实际上使用的是最终位于
libtest中的文件,那么它可能不是理想的。我很确定像./downloader这样的导入是不可能的;如果有什么你可以给它起别名,然后像例如导入它src/downloader,但我不知道你是否对这样的解决方案感兴趣。另外,它实际上只是打字稿部分,我不知道它会如何使用,例如你的测试运行器。
标签: json typescript tsconfig