【问题标题】:Typescrcript path alias cannot find images, styles and other file extensionsTypescript 路径别名找不到图像、样式和其他文件扩展名
【发布时间】:2021-02-17 17:37:54
【问题描述】:

我目前有一些 react typescript 项目,每个项目都使用路径别名,但我面临一个烦人的问题,即使用路径别名导入时,.png.jpg.scss 和在路径自动完成中找不到许多其他内容。 (导入时工作正常,问题只是烦人的自动完成功能无法正常工作,迫使我检查文件夹以获取文件名)

当我使用 import File from '../../../styles/...'; 等相对路径时,自动完成工作正常。我不确定我需要搜索这个错误的确切内容,我已经尝试过,但没有成功。

我正在使用带有 Path Intellisense 扩展名的 vscode,但由于问题发生在 typescript 路径别名上,我认为它没有任何意义。

工作:

不工作:

不显示任何内容,如果我点击ctrl+enter,它会显示几个无用的自动完成,但不会显示文件夹内的文件

tsconfig

{
  "compilerOptions": {
    "target": "es2020",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": false,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "downlevelIteration": true,
    "noEmit": true,
    "jsx": "react",
    "baseUrl": "./src",
    "types": ["cypress"]
  },
  "include": [
    "src"
  ]
}

【问题讨论】:

标签: reactjs typescript visual-studio-code create-react-app


【解决方案1】:

我对 CRA v4 和绝对导入有同样的问题。我最终工作的唯一方法:

  1. 安装Path Intellisense + 将"baseUrl": "src" 添加到您的tsconfig.json
  2. 请勿将"typescript.suggest.paths": false 设置为建议扩展自述文件,将其设置为true
  3. 将以下内容添加到您的 VSCode settings.json
    "path-intellisense.mappings": {
        "/": "${workspaceFolder}",
        "assets": "${workspaceFolder}/src/assets",
        "pages": "${workspaceFolder}/src/pages",
        ... as many lines as folders you have under src, or order paths too
    }

【讨论】:

  • 在没有步骤 3 的情况下运行良好,现在 VSC 可以看到其他文件路径。已投票。
【解决方案2】:

您是否尝试在tsconfig.json 中定义paths 配置?

{
  "compilerOptions": {
    "paths": {
      "@assets/*": ["your/path/to/assets/*"]
    }
  }
}

并像这样使用它:

import Image from '@assets/';

阅读更多关于路径别名here

【讨论】:

  • 我只是尝试过最糟糕的事情,只有主路径有效,它不检索子文件夹。
  • 这如何解决特定的图像(png)导入问题?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-20
  • 2019-09-30
  • 2021-11-29
  • 1970-01-01
  • 2013-02-10
  • 1970-01-01
相关资源
最近更新 更多