无法使tsconfig路径正常工作(TS2307)

时间:2020-03-16 02:20:56

标签: typescript

这是我的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;
}

1 个答案:

答案 0 :(得分:1)

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

要解决此问题,可以将顶级导入移动到模块声明中:

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;
}

Import语句使文件模块和declare module "*.svg"认为的tsc语句成为模块扩充,而不是模块声明。