{Lepus}

GatsbyTypeScript

Gatsby + TypeScriptでSVGファイルをコンポーネントとしてimport出来るようにする

投稿日: September 07, 2020

手順

  1. gatsby-plugin-react-svg をインストールする
  2. gatsby-config.jsの plugins にgatsby-plugin-react-svgを追記する
  3. svg の型定義ファイルを作成する
  4. tsconfig.jsonで型定義ファイルを認識させる

手順詳細

$ yarn add gatsby-plugin-react-svg
// gatsby-config.js

plugins: [
  {
    resolve: "gatsby-plugin-react-svg",
    options: {
      rule: {
        include: /assets/, // 読み込みたいSVGファイルが置いてあるフォルダを指定する
      },
    },
  },
]

普通の JavaScript であれば、ここまでの設定で以下のように SVG ファイルをコンポーネントとして import 出来るようになります。

import Icon from "./path/assets/icon.svg"

// ...
;<Icon />

しかし TypeScript で開発している場合は、以下の様に型定義ファイルがないことでエラーが発生します。 Type error when tempting importing svg file なので型定義ファイルを追加します。

// src/index.d.ts

declare module "*.svg" {  import React = require("react")  export const ReactComponent: React.SFC<React.SVGProps<SVGSVGElement>>  const src: string  export default src}

tsconfig.json に、下記を追記しこの型定義ファイルを読み込めば完了です。

// tsconfig.json

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

書いた人

profile picture

Kosei Sakaguchi

フロントエンドエンジニア / WEBデザイナー

福岡市を拠点に、フリーランスとしてWEBサイト制作やWEB/モバイルアプリケーション開発を行っています。新しい技術と洋服と猫とが好きです!制作実績はWorksへどうぞ! ご興味を持っていただけましたら、お気軽にお声がけください🔥

{Lepus}

Writer's social medias:

© 2020 Lepus