7
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Next.jsでSVGをコンポーネントとしてImportするやり方

Last updated at Posted at 2021-03-15

やりたい事

Next.js x TypeScriptでSVGをこんな感じでimportして使いたい。

import IconPenguin from "./IconPenguin.svg"

export const Component = () => (
  <div>
    <IconPenguin/>
  </div>
);

やり方

SVGRというsvgファイルをReactコンポーネントとして読み込めるようにしてくれるツールを利用する。

npm install @svgr/webpack

next.config.jsを作成して以下を記述。

module.exports = {
  webpack(config) {
    config.module.rules.push({
      test: /\.svg$/,
      use: ["@svgr/webpack"]
    });
    return config;
  }
};

TypeScriptを使用している場合は以下のようなエラーが出るので、

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

index.d.tsを作成して以下を記述。

declare module '*.svg'

参考

Next.jsでsvgを使用する
https://qiita.com/shn_kg/items/6660fb9ee63b2402de6a

SVGR
https://github.com/gregberge/svgr

7
1
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
7
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?