VSCode 中 TypeScript 文件中的绝对模块路径解析

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37606571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:33:10  来源:igfitidea点击:

Absolute module path resolution in TypeScript files in VSCode

moduletypescriptvisual-studio-code

提问by Robert Koritnik

I can't seem to convince VSCode to resolve absolute TypeScript module paths. Relative paths work, but absolute don't. I would like VSCode to resolve module paths from ./srcfolder on.

我似乎无法说服 VSCode 解析绝对 TypeScript 模块路径。相对路径有效,但绝对路径无效。我希望 VSCode 从./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 is of course not supposed to be used
import { Interface } from 'c:/..../src/api/interfaces';

The last one of course doesn't count as each developer's project path is highly likely different. But even if we'd all set a system variable %ProjectXRoot%we can't use this variable in the code. VSCode will not resolve such module path. I've tried.

最后一个当然不算数,因为每个开发人员的项目路径很可能不同。但是即使我们都设置了一个系统变量,%ProjectXRoot%我们也不能在代码中使用这个变量。VSCode 不会解析此类模块路径。我试过了。

// won't work
import { Interface } from '%ProjectXRoot%/api/interfaces';

Currently installed versions
? TypeScript: 1.8.10
? VSCode: 1.1.1

当前安装的版本
?打字稿:1.8.10
?VSCode:1.1.1

Question

问题

I've tried to somehow configure VSCode to resolve absolute module paths, but can't seem to do so. I've tried configuring tsconfig.json(in the project root) by adding baseUrlon two different places.

我试图以某种方式配置 VSCode 来解析绝对模块路径,但似乎无法这样做。我尝试通过在两个不同的地方添加来配置tsconfig.json(在项目根目录中)baseUrl

{
    ...
    "compilerOptions": {
        "baseUrl": "./src", // doesn't work
        ...
    },
    "baseUrl": "./src", // doesn't work either
    ...
}

I've tried values like src, ./srcand ./src/but none of them work in any of the upper configuration place.

我试过值喜欢src./src./src/但他们没有任何上配置的地方工作。

So how does one configure VSCodeto resolve absolute module paths from a certain folder?

那么如何配置 VSCode来解析某个文件夹中的绝对模块路径呢?

If that's not possible it would be at least better to resolve absolute paths from project root. I have no idea how VSCode determines that? Is it where you Open Folderor is it where the .vscodefolder is? No idea. But it would still be a viable solution for absolute paths. I've tried using ~similar to VS but to no avail either.

如果这是不可能的,那么从项目根目录解析绝对路径至少会更好。我不知道 VSCode 是如何确定的?它是您打开文件夹的位置还是.vscode文件夹的位置?不知道。但它仍然是绝对路径的可行解决方案。我试过使用~类似于 VS 但也无济于事。

Edit(unresolved)

编辑(未解决)

As @steinsopoints out in his answer all modules starting with /, ./or ../are considered relative. Especially the first one surprised me completely as I usually consider that a project root-relative path. But this fact basically means that the main questionnow becomes: How can I provide module imports as absolute paths(from some projectroot folder path)at all? Starting paths with slashes usually meant absolute, but in this case it doesn't.

正如@steinso在他的回答中指出的,所有以/, ./or开头的模块../都被认为是相对的。特别是第一个完全让我惊讶,因为我通常认为这是一个项目根相对路径。但这个事实基本上意味着现在的主要问题变成了:我怎样才能将模块导入提供为绝对路径(来自某个项目根文件夹路径)?以斜线开头的路径通常意味着绝对,但在这种情况下并非如此。

Even when I set compiler option moduleResolutionto classic(so module resolution wont be looking into node_modulesfolder) the second set of imports above should actually all workas per Microsoft's linked document. But for some reason I still get red squiggly lines in VSCode and errors during compilation.

即使我将编译器选项设置moduleResolutionclassic(因此模块解析不会查看node_modules文件夹),上面的第二组导入实际上应该按照 Microsoft 的链接文档工作。但出于某种原因,我仍然在 VSCode 中看到红色波浪线,并且在编译过程中出现错误。

So how can I import a specific project module without providing exact relative pathto it but rather just its own project-relative path?

那么如何在不提供确切的相对路径的情况下导入特定的项目模块,而只是提供它自己的项目相对路径呢?

回答by Lekhnath

To be able to use absolute paths from import in typescript using VSCode you should be using next version of typescript - typescript@nextwhich is typescript v2. For that do the following:

为了能够使用 VSCode 在打字稿中使用导入的绝对路径,您应该使用下一个版本的打字稿 -typescript@next这是打字稿 v2。为此,请执行以下操作:

  1. Install typescript@next via npm , for installing typescript v2.x

    npm i typescript@next -D

  2. In VSCode

    i) goto File > Preferences > Workspace Settings[This generates .vscodedirectory at project root and initializes the settings.jsonfile]

    ii) Put the following key:valuepair in settings.jsonfile

    "typescript.tsdk": "node_modules/typescript/lib"

  3. In tsconfig.jsonadd following key:value pair to 'compilerOptions'

  1. 通过 npm 安装 typescript@next,用于安装 typescript v2.x

    npm i typescript@next -D

  2. 在 VSCode 中

    i) 转到文件 > 首选项 > 工作区设置[这会.vscode在项目根目录生成目录并初始化settings.json文件]

    ii) 将以下key:value对放在settings.json文件中

    "typescript.tsdk": "node_modules/typescript/lib"

  3. tsconfig.json添加以下键:值对到'compilerOptions'

{
  "compilerOptions" : {
    "baseUrl": "./",
    "paths" : {
      "src/*": ["./src/*"]
    }
  }
}
  1. Reload VSCode
  1. 重新加载 VSCode

If you have the following directory structure:

如果您有以下目录结构:

+ node_modules
+ src
| + app
| |  + shared
| |  |  -service.ts
| |  -main.ts
+ typings
- tsconfig.json
- webpack.config.json
- package.json
- index.html

Then to import /src/app/shared/service.tsfrom main.tsyou could now import {} from 'src/app/shared/service;

然后现在可以/src/app/shared/service.tsmain.ts您那里导入import {} from 'src/app/shared/service

If you are using webpackand ts-loaderfor transpiling the .tsfiles you should add following to the resolvesection of webpack.config.jsconfiguration file.

如果您正在使用webpackts-loader转换.ts文件,您应该将以下内容添加到配置文件resolve部分webpack.config.js

resolve: {
    extensions: ['', '.js', '.ts'],
    alias: {
      "src": path.resolve('./src')
    }
  }

Please refer to thisfor absolute module resolution.

请参考这里的绝对模块分辨率。

回答by steinso

You need to specify:

您需要指定:

    "compilerOptions": {
        "moduleResolution": "classic"
        ...

The base path will then default to the directory of your tsconfig.json, add rootDirin compilerOptions to change it.EDIT: This does not seem to have any effect.

基本路径将默认为您的 tsconfig.json 目录,添加 rootDircompilerOptions 以更改它。编辑:这似乎没有任何影响。

This will allow imports such as:

这将允许导入,例如:

import { Interface } from 'api/interfaces';

Note that any path starting with .or ../or /is considered relative.

请注意,任何以.or../或 or开头的路径都/被认为是相对的。

Edit:Module resolution

编辑:模块分辨率

Be aware of how the modules are resolved. The module path is still some what relative to the current file.

请注意模块的解析方式。模块路径仍然是相对于当前文件的一些内容。

Let's use an example to illustrate for the current scenario:

我们用一个例子来说明当前的场景:

Let's say you import { Interface } from "api/interfaces", from source file /src/views/View.ts. Typescript would then look for the module in the following paths:

假设你import { Interface } from "api/interfaces",从源文件/src/views/View.ts. 然后打字稿会在以下路径中查找模块:

  1. /src/views/api/interfaces.ts
  2. /src/api/interfaces.ts
  3. /api/interfaces.ts
  1. /源/视图/api/interfaces.ts
  2. /源/api/interfaces.ts
  3. /api/interfaces.ts

Note:how this still makes it relative, imagine if you import {Home} from "Home/Home"when you are located in /src/views/View.ts. In this case it would work even if the path is /src/views/Home/Home.

注意:这仍然使它具有相对性,想象一下,如果您import {Home} from "Home/Home"位于/src/views/View.ts. 在这种情况下,即使路径是/src/views/Home/Home.

These are the possible resolutions:

这些是可能的解决方案:

  1. /src/views/Home/Home-> Note how this would work.
  2. /src/Home/Home
  3. /Home/Home
  1. /src/views/ Home/Home-> 请注意这是如何工作的。
  2. /源/Home/Home
  3. /Home/Home

More information can be found here: http://www.typescriptlang.org/docs/handbook/module-resolution.html

更多信息可以在这里找到:http: //www.typescriptlang.org/docs/handbook/module-resolution.html

回答by RWDJ

For others who come here, if you've setup paths correctly:

对于来到这里的其他人,如果您正确设置了路径:

{
  …
  "compilerOptions": {
    …
    "baseUrl": ".",
    "paths": {
      "~/*": ["app/assets/javascript/*"],
      "*": ["node_modules/*", "app/assets/javascript/packs/*"]
    }
  }
}

And you're still having issues, maybe try reloading vscode: cmd+ shift+ Pand type reload window.

而你仍然有问题,也许尝试重装vscode:cmd+ shift+P和类型reload window

It just randomly stopped working for me and reporting problems. I spent around 20 minutes online trying to figure out what changed, only to realize that VS Code can glitch on absolute path resolution.

它只是随机停止对我来说有效并报告问题。我在网上花了大约 20 分钟试图找出发生了什么变化,结果发现 VS Code 可能会在绝对路径解析上出现故障。