jacobmischka/gatsby-plugin-react-svg

Typescript Error

jonohewitt opened this issue · 5 comments

Hi, thanks a lot for this plugin! I'm trying to use it with Typescript and have set up a custom typescript definition as described in the readme but I'm still getting hit with the error:

import Example from "../images/example.svg"

Cannot find module '../images/example.svg' or its corresponding type declarations.ts(2307)

My config files are:

// gatsby-config.ts

...
    {
      resolve: "gatsby-plugin-react-svg",
      options: {
        rule: {
          include: /images\/.*\.svg/,
        },
      },
    },
...
// declarations.d.ts

declare module "*.svg" {
  const content: any
  export default content
}
// tsconfig.json

{
  "$schema": "https://json.schemastore.org/tsconfig",
  "display": "Node 16",

  "compilerOptions": {
    "lib": ["es2021", "DOM"],
    "module": "commonjs",
    "target": "es2021",
    "jsx": "react",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["./src/declarations.d.ts"]
}

I've checked the image is at the specified path and the SVG does load to the page successfully. Do you have any idea what might be causing this? Thanks very much for any help - I realise this isn't anything wrong with the plugin itself.

also getting this error in a vanilla gatsby project

Is it building? Is it an error or a hint?

It builds fine. I've followed all the instructions to a T,

For the import:

import HSIcon from '../../../assets/images/HazelSoftware_Logo_V1_Icon_FullColor.svg'

it just says:

Cannot find module '../../../assets/images/HazelSoftware_Logo_V1_Icon_FullColor.svg' or its corresponding type declarations

with type defs file index.d.ts

import * as React from 'react'
import { CSSProperties, DOMAttributes } from 'react'

export interface CustomCSS extends CSSProperties {
  [key: `--${string}`]: string | number
}

// images

declare module '*.jpg'
declare module '*.png'

declare module '*.svg' {
  const content: any
  export default content
}

and config:

{
      resolve: 'gatsby-plugin-react-svg',
      options: {
        rule: {
          include: /assets\/images/,
        },
      },
    },

Yeah, we don't generate types for the SVG. PRs welcome but no idea how you're even supposed to do that. Regardless, it's probably an upstream kind of thing.

This is what worked for me:

  • in globals.d.ts (at the root folder)
declare module "*.svg" {
  const content: any
  export default content
}