Solve the problem of “XXX or its corresponding type declaration cannot be found” when introducing the picture error in TS development

Time:2022-5-27

When using TS development, introduce picture error reporting

import img from '../../assets/images/foo.png';

Cannot find module ‘.. /.. / assets / images / foo. PNG’ or its corresponding type declaration.

Because typescript does not recognize non code resources. We need to take the initiative to declare this module

Method 1: Source: reference link
Create a new TS declaration file: images d.ts

declare module '*.svg'
declare module '*.png'
declare module '*.jpg'
declare module '*.jpeg'
declare module '*.gif'
declare module '*.bmp'
declare module '*.tiff'

The project will be read automatically during compilation d. TS this type of file, so we don’t need to load it manually. Placed in tsconfig JSON under the folder configured by the include attribute.

Method 2:
If your project was created using:

npx create-react-app my-app --template typescript
# or
yarn create react-app my-app --template typescript

There will be a react app env in your SRC directory d. TS file. The contents are as follows:

/// <reference types="react-scripts" />

This file uses the triple slash instruction to introduce the type declaration file of react scripts, which is in the target file react app d. TS declares the types of resources such as various pictures.
Document content:

/// <reference types="node" />
/// <reference types="react" />
/// <reference types="react-dom" />

declare namespace NodeJS {
  interface ProcessEnv {
    readonly NODE_ENV: 'development' | 'production' | 'test';
    readonly PUBLIC_URL: string;
  }
}

declare module '*.avif' {
  const src: string;
  export default src;
}

declare module '*.bmp' {
  const src: string;
  export default src;
}

declare module '*.gif' {
  const src: string;
  export default src;
}

declare module '*.jpg' {
  const src: string;
  export default src;
}

declare module '*.jpeg' {
  const src: string;
  export default src;
}

declare module '*.png' {
  const src: string;
  export default src;
}

declare module '*.webp' {
    const src: string;
    export default src;
}

declare module '*.svg' {
  import * as React from 'react';

  export const ReactComponent: React.FunctionComponent<React.SVGProps<
    SVGSVGElement
  > & { title?: string }>;

  const src: string;
  export default src;
}

declare module '*.module.css' {
  const classes: { readonly [key: string]: string };
  export default classes;
}

declare module '*.module.scss' {
  const classes: { readonly [key: string]: string };
  export default classes;
}

declare module '*.module.sass' {
  const classes: { readonly [key: string]: string };
  export default classes;
}

Just tsconfig JSON includes the SRC directory, which can be imported normally.