Importing SVG Files In Typescript React Project
Howto
To display SVG files on the page (as e.g. icons or images or other elements), there are several ways depending on circumstances and requirements. For this case, I'm mostly concerned with React project written in Typescript - though for JS (and non-React) projects some of the below options apply as well.
Perhaps the simplest way is to just add it to the component "as is" - because it's a valid markup, things like
export const ComponentWithSvg = () => (
would do just fine. Not reusable, not structured, not viewable independently - but it'd work.
If the project was created with Create React App or uses Parcel v2 or was appropriately configured to process assets automatically, another option is to import it like e.g.
import iconPath from './iconFile.svg';
export const ComponentWithSvg = () => ( <> </> );
or in case that imports file data as string, it should be possible to use it as a variable inside the component as e.g.
import icon from './iconFile.svg';
export const ComponentWithSvg = () => ( <> {icon} </> );
There's also an option to turn the icon into a ReactComponent and use it as such - though a bit more work, I think it's the most structurally sound way:
-
Add type declaration for the .svg files by creating
./src/@types/assets/index.d.ts
file with content:declare module "*.svg" { import React = require("react"); const ReactComponent: React.FC<React.SVGProps
>; export default ReactComponent; } -
In
tsconfig.json
, configure typeRoots parameter to include the types:{ ... "typeRoots": ["./src/@types", "./node_modules/@types"], ... }
-
Import and use it as a component:
import React from "react"; import { ReactComponent as SVGIcon } from "./icon.svg";
export const ComponentWithSvg = () => ( <>
</> );