在 VS Code 中:[ts] 找不到模块“@src/xxx”

dan*_*aze 5 typescript visual-studio-code

所以,我正在使用这个tsconfig.json

{
  "compilerOptions": {
    "baseUrl": ".",
    "declaration": true,
    "module": "ES6",
    "moduleResolution": "node",
    "outDir": "./lib/",
    "paths": {
      "@src/*": ["src/*"]
    },
    "preserveConstEnums": true,
    "removeComments": true,
    "sourceMap": true,
    "target": "ES6"
  },
  "include": [
    "global.d.ts",
    "src/**/*.ts"
  ]
}
Run Code Online (Sandbox Code Playgroud)

在哪里可以看到别名@src是为我的代码定义的。

tsc/webpack构建所有内容都没有问题,但是在 VS Code 中进行编辑时,当我将某些内容作为

import { xxx } from '@src/xxx';
Run Code Online (Sandbox Code Playgroud)

有同样问题的人吗?对我来说,看到这一点很奇怪,因为如果它正确编译/构建(来自 tscwebpack),这意味着配置是正确的。那么为什么 VS Code 会显示这个错误消息呢?这只是烦人,但我想解决它。

tsconfig.json文件也使用标准名称(没有自定义-p选项tsc)所以,VS Code 应该能够自动读取它,对吧?或者IDE需要任何额外的配置?

Ole*_*nyk 9

我遇到过同样的问题。在我的情况下运行Cmd+Shift+P > Typescript: Restart TS Server没有技巧和错误消息消失

  • 天哪...我只花了 3 个小时在这上面,直到你救了我。 (2认同)

dan*_*aze 9

很长一段时间后(我已经忘记了这个问题......)我让它工作了(不知道在发布原始问题时是否可能)。

我会在这里写下我所做的,以防对其他人有帮助:)

基本上,我需要以下内容:

1. 定义路径tsconfig.json

这是最初的问题,但也将其包含在此处以完成:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@src": ["src"],
      "@src/*": ["src/*"],
    }
}
Run Code Online (Sandbox Code Playgroud)

2. 安装tsconfig-paths

npm i -D tsconfig-paths

如果您也使用webpack添加tsconfig-paths-webpack-plugin并添加插件,webpack.config.js如下所示:

const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');

module.exports = {
  // ...
  resolve: {
    extensions: ['.ts', '.tsx', '.js', '.json'],
    plugins: [new TsconfigPathsPlugin({ configFile: 'tsconfig.json' })],
  },
};
Run Code Online (Sandbox Code Playgroud)

如果您使用NextJS,插件的配置如下所示next.config.js

const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');

module.exports = {
  webpack: (config) => {
    config.resolve.plugins.push(
      new TsconfigPathsPlugin({ configFile: 'tsconfig.json' })
    );

    return config;
  },
};

Run Code Online (Sandbox Code Playgroud)

我不确定这是否只是 VS Code 的改进(因此我的问题在我发布问题后的一年半内自动修复),但这就是我现在正在使用的并且工作正常。希望对其他人也有帮助:)

注意(2022/07/31 with TS 4.6.4) -TsconfigPathsPlugin如果您尝试使用任何其他加载器从 TS 导入非 ts 代码(即资产),仍然需要。

例子:

import icon from '@assets/icon.svg';
Run Code Online (Sandbox Code Playgroud)

我发现仍然需要 webpack 插件来实现这一点。