LoginSignup
4
0

More than 1 year has passed since last update.

Gatsbyでsvgをimport出来ない場合の備忘録

Last updated at Posted at 2023-01-16

こんにちは。
今回はGatsbyを使用する中でsvgファイルをimportしたいけど、エラーが出て出来ない場合の備忘録として記します。

私の環境

├── @emotion/react@11.10.5
├── @emotion/styled@11.10.5
├── @mdx-js/react@2.2.1
├── @types/node@18.11.18
├── @types/react-dom@18.0.10
├── @types/react@18.0.26
├── gatsby-plugin-emotion@8.4.0
├── gatsby-plugin-image@3.4.0
├── gatsby-plugin-mdx@5.4.0
├── gatsby-source-filesystem@5.4.0
├── gatsby@5.4.0
├── react-dom@18.2.0
├── react@18.2.0
└── typescript@4.9.4

:frowning2: エラーとなる状況

import logo from "../assets/logo.svg"

↑こんな感じでimportしてもパスがエラーになってしまう。

:bulb: 解決法

ステップ1

適当な.d.tsファイルを作ります。今回はsvg.d.tsとします。このファイルに以下のような記述をします。

declare module "*.svg"

ステップ2

次にtsconfig.jsoncompilerOptionsに以下のような記述をします。

"baseUrl": ".",
    "paths": {
      "*": ["src/assets/*"]
    }, 

:v: これでエラーなくsvgの表示ができた

gatsby-plugin-react-svgというプラグインもあるのですが、私の環境下ではvulnerabilitiesが複数出てしまい厄介だったのでなんとかプラグイン無しで出来ないか模索した結果こうなりました。

React、Typescript、Gatsbyどれを取っても初心者中の初心者ですので、他にもっと良い方法があったらコメントでご指摘頂けますと幸いです!

参考文献

4
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
0