首页 > 解决方案 > 无法使 tsconfig 路径正常工作 (TS2307)

问题描述

这是我的tsconfig.json

{
    "compilerOptions": {
        "strict": true,
        "importHelpers": false,
        "inlineSources": true,
        "noEmitOnError": true,
        "pretty": true,
        "module": "esnext",
        "noImplicitAny": true,
        "suppressImplicitAnyIndexErrors": false,
        "removeComments": false,
        "preserveConstEnums": false,
        "sourceMap": true,
        "lib": ["es2018","dom"],
        "skipLibCheck": false,
        "outDir": "dist",
        "target": "es2018",
        "declaration": false,
        "resolveJsonModule": false,
        "esModuleInterop": true,
        "jsx": "preserve",
        "moduleResolution": "node",
        "allowSyntheticDefaultImports": true,
        "baseUrl": ".",
        "noEmit": true,
        "paths": {
            "@/*": ["./src/*"],
        },
    },
    "files": [
        "src/index.tsx"
    ],
    "include": [
        "src/**/*.d.ts"
    ]
}

跑步:

$ node_modules/.bin/tsc --noEmit
src/components/App.tsx:13:27 - error TS2307: Cannot find module '@/icons/info-circle.svg'.

13 import InfoCircleSvg from '@/icons/info-circle.svg';
                             ~~~~~~~~~~~~~~~~~~~~~~~~~

src/components/pages/HomePage.tsx:2:20 - error TS2307: Cannot find module '@/images/gambit.jpg'.

2 import imgSrc from '@/images/gambit.jpg';
                     ~~~~~~~~~~~~~~~~~~~~~


Found 2 errors.

但这些文件确实存在:

$ ll src/icons/info-circle.svg
-rw-r--r-- 1 mpen mpen 479 Mar 15 18:51 src/icons/info-circle.svg

paths我已经尝试了所有我能想到的有和没有的排列*,但我无法解决任何问题。baseUrl设置.为许多教程和帖子所建议的。我错过了什么?

是文件扩展名出错tsc了吗?因为 webpack 可以很好地处理它们,而且我有一个选项应该选择的images.d.ts文件:include

import { ElementType } from "react";

declare module "*.png" {
  const content: string;
  export default content;
}

declare module "*.jpg" {
  const content: string;
  export default content;
}

declare module "*.jpeg" {
  const content: string;
  export default content;
}

declare module "*.gif" {
  const content: string;
  export default content;
}

declare module "*.svg" {
  const content: ElementType<React.SVGProps<SVGSVGElement> & { title?: string, desc?: string }>;
  export default content;
}

标签: typescript

解决方案


问题不在于路径,而在于声明文件。

要修复它,您可以将顶级导入移动到模块声明中:

declare module "*.svg" {
    import { ElementType, SVGProps } from 'react';
    const content: ElementType<SVGProps<SVGSVGElement> & { title?: string, desc?: string }>;
    export default content;
}

或将其完全删除,然后:

declare module "*.svg" {
    const content: React.ElementType<React.SVGProps<SVGSVGElement> & { title?: string, desc?: string }>;
    export default content;
}

导入语句使文件模块,因此由模块扩充而不是模块声明declare module "*.svg"考虑的语句。tsc


推荐阅读