我似乎无法说服 Visual Studio Code 解析绝对 TypeScript 模块路径。相对路径有效,但绝对路径无效。我希望 Visual Studio Code 能够解析来自./src
文件夹上。
// This works when source file is in /src/here/there/file.ts
// and importing an interface in /src/api/interfaces.ts
import { Interface } from '../../api/interfaces';
// This doesn't work
import { Interface } from 'api/interfaces';
import { Interface } from '/api/interfaces';
import { Interface } from 'src/api/interfaces';
import { Interface } from '/src/api/interfaces';
// This works, but it is of course not supposed to be used
import { Interface } from 'c:/..../src/api/interfaces';
最后一个当然不算数,因为每个开发人员的项目路径很可能不同。但即使我们都设置了一个系统变量%ProjectXRoot%
我们不能在代码中使用这个变量。 Visual Studio Code 不会解析此类模块路径。我试过了。
// Won't work
import { Interface } from '%ProjectXRoot%/api/interfaces';
当前安装的版本
•打字稿:1.8.10
VSCode:1.1.1
Question
我尝试以某种方式配置 Visual Studio Code 来解析绝对模块路径,但我似乎无法这样做。我尝试过配置tsconfig.json(在项目根目录中)添加baseUrl
在两个不同的地方。
{
...
"compilerOptions": {
"baseUrl": "./src", // Doesn't work
...
},
"baseUrl": "./src", // Doesn't work either
...
}
我尝试过类似的值src
, ./src
and ./src/
,但它们都不能在任何较高配置的地方工作。
So 如何配置 Visual Studio Code解析某个文件夹中的绝对模块路径?
如果这是不可能的,那么至少从项目根目录解析绝对路径会更好。 Visual Studio Code 如何确定这一点?是你的地方吗打开文件夹或者是在哪里.vscode文件夹是?
但它仍然是绝对路径的可行解决方案。我尝试过使用~
与 Visual Studio 类似,但也无济于事。
(Unresolved)
--
As steinso指出在他的回答 https://stackoverflow.com/questions/37606571/absolute-module-path-resolution-in-typescript-files-in-vscode/37655471#37655471,所有模块以/
, ./
or ../
被认为是相对的。尤其是第一个完全让我惊讶,因为我通常认为这是一个项目根相对路径。
But this fact basically means that the main question now becomes: How can I provide module imports as absolute paths (from some project root folder path) at all? Starting paths with slashes usually meant absolute, but in this case it doesn't.
即使我设置了编译器选项moduleResolution
to classic
(所以模块解析不会考虑node_modules
文件夹)上面的第二组导入实际上应该all work根据微软的链接文档。但由于某种原因,我仍然在 Visual Studio Code 中看到红色波浪线,并且在编译过程中出现错误。
那么我怎样才能导入特定的项目模块而不提供确切的相对路径到它,而只是它自己的项目相对路径?