Search code examples
reactjstypescriptsvgcreate-react-app

How do I import an SVG into a component using Create React App and TypeScript?


I have a React project written in JS that I am converting to TS. Using JS, this works:

import { ReactComponent as IconPerson } from '../../../icons/person.svg';

Using TS, I get this error:

Cannot find module '../../../icons/person.svg' or its corresponding type declarations.

I have added the following to a new index.d.ts file:

declare module '*.svg';

I have also added the index.d.ts file to the include array in my tsconfig.json:

{
  include: ["src", "**/*.ts", "**/*.tsx", "index.d.ts"]
}

What am I missing?


Solution

  • This works for me:

    declare module '*.svg' {
      import React = require('react');
      export const ReactComponent: React.FC<React.SVGProps<SVGSVGElement>>;
    }
    

    Credit: https://stackoverflow.com/a/54122106/2262604

    It seems strange to me creating a ReactComponent variable, but I no longer get any TS errors.