jacobmischka / gatsby-plugin-react-svg

Adds svg-react-loader to gatsby webpack config
https://www.npmjs.com/package/gatsby-plugin-react-svg
MIT License
70 stars 21 forks source link

Typescript Error #48

Open jonohewitt opened 2 years ago

jonohewitt commented 2 years ago

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.

ortonomy commented 2 years ago

also getting this error in a vanilla gatsby project

jacobmischka commented 2 years ago

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

ortonomy commented 2 years ago

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/,
        },
      },
    },
jacobmischka commented 2 years ago

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.

AtRiskMedia commented 1 year ago

This is what worked for me: