Absolute module path resolution in TypeScript files in Visual Studio Code
我似乎无法说服Visual Studio Code解析绝对TypeScript模块路径。相对路径有效,但绝对无效。我希望Visual Studio Code可以解析
1 2 3 4 5 6 7 8 9 10 11 12 | // 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'; |
当然,最后一个不算在内,因为每个开发人员的项目路径很可能是不同的。但是,即使我们都设置了系统变量
1 2 | // Won't work import { Interface } from '%ProjectXRoot%/api/interfaces'; |
Currently installed versions
? TypeScript: 1.8.10
? VSCode: 1.1.1
题
我试图以某种方式配置Visual Studio Code来解析绝对模块路径,但是我似乎无法这样做。我尝试通过在两个不同的地方添加
1 2 3 4 5 6 7 8 9 | { ... "compilerOptions": { "baseUrl":"./src", // Doesn't work ... }, "baseUrl":"./src", // Doesn't work either ... } |
我尝试过
那么,如何配置Visual Studio Code来解析某个文件夹中的绝对模块路径?
如果这不可能,那么从项目根目录解析绝对路径至少会更好。 Visual Studio Code如何确定这一点?它是在您打开文件夹的位置还是.vscode文件夹的位置?
但这对于绝对路径仍然是可行的解决方案。我尝试使用类似于VisualStudio的
(未解决)
-
正如steinso在他的答案中指出的那样,所有以
但是这个事实基本上意味着,现在的主要问题变成了:我如何才能完全将模块导入作为绝对路径(来自某些项目根文件夹路径)提供?以斜杠开头的路径通常表示绝对路径,但在这种情况下不是绝对路径。
即使当我将编译器选项
那么,如何导入特定的项目模块而不提供确切的相对路径,而仅提供其自己的项目相对路径?
为了能够使用从Visual Studio Code中导入TypeScript的绝对路径,您应该使用下一版本的TypeScript-
通过npm安装typescript @ next。用于安装TypeScript v2.x
在Visual Studio Code中
i)转到菜单文件→首选项→工作区设置(这将在项目根目录生成
ii)将以下
在
1 2 3 4 5 6 7 8 | { "compilerOptions" : { "baseUrl":"./", "paths" : { "src/*": ["./src/*"] } } } |
如果您具有以下目录结构:
1 2 3 4 5 6 7 8 9 10 11 | + node_modules + src | + app | | + shared | | | -service.ts | | -main.ts + typings - tsconfig.json - webpack.config.json - package.json - index.html |
然后要从
如果使用
1 2 3 4 5 6 | resolve: { extensions: ['', '.js', '.ts'], alias: { "src": path.resolve('./src') } } |
有关绝对模块分辨率,请参考此内容。
您需要指定:
1 2 3 | "compilerOptions": { "moduleResolution":"classic" ... |
然后,基本路径将默认设置为tsconfig.json的目录,在compileOptions中添加
这将允许进口,例如:
1 | import { Interface } from 'api/interfaces'; |
请注意,以
编辑:模块分辨率
注意如何解决模块。模块路径仍然是相对于当前文件的路径。
让我们用一个例子来说明当前情况:
假设您
注意:这仍然是相对的,想象一下位于
这些是可能的解决方法:
更多信息可以在这里找到:
http://www.typescriptlang.org/docs/handbook/module-resolution.html
如果您正确设置了路径:
1 2 3 4 5 6 7 8 9 10 11 | { … "compilerOptions": { … "baseUrl":".", "paths": { "~/*": ["app/assets/javascript/*"], "*": ["node_modules/*","app/assets/javascript/packs/*"] } } } |
并且,如果仍然有问题,请尝试重新加载Visual Studio代码:Cmd + Shift + P并键入
它只是随机停止为我工作,并正在报告问题。我花了大约20分钟的时间在网上尝试找出发生了什么变化,只是意识到Visual Studio Code可能会干扰绝对路径分辨率。