How to import a svg file in React?

Viewed 2946

I have a custom React + Typescript + Webpack project. I need to import a simple .svg file and use it in a component. Typescript claims it:

Cannot find module

I've installed svgr, added it to my webpack config, created a custom.d.ts file allowing svg import in typescript and specified it in the tsconfig.json. Nothing works (I run the component in Storybook for the moment).

Here is my webpack:

 module: {
      rules: [
        {
          test: /\.(ts|js)x?$/,
          exclude: /node_modules/,
          use: { loader: "babel-loader" },
        },
        { test: /\.css$/, use: ["style-loader", "css-loader"] },
        { test: /\.svg$/, use: ["@svgr/webpack"] },
        { test: /\.(png|svg|jpg|gif)$/, use: ["file-loader"] },
      ],
    },

My component

import React, { useEffect } from "react";
import Account from "./account.svg";

export default function Icon({ icon }) {
  return (
    <div>
      <Account/>
    </div>
  );
}

The custom.d.ts

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

// added to tsconfig.json
"include": ["./src/**/*", "./custom.d.ts"],

The svg is a simple <svg><path blabla/></svg> file.

How to fix this?

1 Answers

I had the same problem, and I found the solution here.

I personnaly used this method :

  1. I imported my logo as a ReactComponent.

  2. Then I used it in my code :)

import React from "react";
import { ReactComponent as MySvgFile } from "path/to/file.svg";

export default function MyComponent() {
  return (
    <div>
      <MySvgFile />
    </div>
  );
}

Related