How to import a svg file in React?
Asked Answered
T

1

6

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?

Teatime answered 24/10, 2020 at 13:58 Comment(0)
B
2

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>
  );
}
Benempt answered 17/12, 2020 at 4:2 Comment(3)
Where does the <Logo /> come from? What do you do with mySvgFile?Smokeless
Oops, sorry, it was my real component name ! I'll correct for <mySvgFile /> !Benempt
This does not address the typescript issues at all and won't compile in typescript (without extra steps)Southard

© 2022 - 2024 — McMap. All rights reserved.