绝对路径的 TS Config 嵌套别名不起作用

bil*_*man 5 typescript reactjs vite

我正在尝试为与 Vite 捆绑的 React 应用程序设置路径别名tsconfig.json。这是我的相关部分tsconfig.json

{
  "compilerOptions": {
    "baseUrl": ".",
    ...
    "paths": {
      "*": ["src/*", "node_modules/*"],
      "components/*": ["src/components/*"],
      "containers/*": ["src/containers/*"],
      "pages/*": ["src/constants/*"],
      "store/*": ["src/store/*"],
      "types/*": ["src/types/*"],
      "NestedFolder/*": [
        "src/components/NestedFolder/*"
      ],
    }
  },
  "include": ["src/**/*", "*"]
}
Run Code Online (Sandbox Code Playgroud)

唯一的问题是NestedFolder. 当我以这种方式导入时,一切正常:

import { ComponentName } from "components/NestedFolder/types";
Run Code Online (Sandbox Code Playgroud)

但是,嵌套别名失败:

import { ComponentName } from "NestedFolder/types";

// error 
EslintPluginImportResolveError: typescript with invalid interface loaded as resolver
Occurred while linting .../src/components/NestedFolder/canvas/index.ts:1
Rule: "import/namespace"

// error on hover in VS Code
Unable to resolve path to module 'NestedFolder/types'.eslintimport/no-unresolved
Run Code Online (Sandbox Code Playgroud)

我想做嵌套组件,因为我有几个嵌套 3-4 层的文件夹,如果能更清晰地查看我的导入内容那就太好了。有没有办法做到这一点?

小智 3

您需要安装vite-tsconfig-paths 插件才能使用 TypeScript 和 Vite 设置路径别名。如果没有任何变化并且您正在使用 VSCode,请确保按Ctrl+Shift+PCmd+Shift+P,键入restart,然后选择命令来重新启动 TypeScript 服务器:TypeScript: Restart TS server