Unable to import svg files in typescript Unable to import svg files in typescript typescript typescript

Unable to import svg files in typescript


If you use webpack, you can do this by creating a custom types file.

Create a file named custom.d.ts with the following content:

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

Add the custom.d.ts to tsconfig.json as below

"include": ["src/components", "src/custom.d.ts"]

Source: https://webpack.js.org/guides/typescript/#importing-other-assets


Thanks smarx for pointing out use require(). So in my case it should be:

const logo = require("./logo.svg") as string;

which works fine in *.tsx files


Add a custom.d.ts file (I created it on the root path of my src dir) with the correct type (thanks to RedMatt):

declare module '*.svg' {  const content: React.FunctionComponent<React.SVGAttributes<SVGElement>>;  export default content;}

Install svg-react-loader or some other, then:

  • Use it as the main svg loader
  • Or if you're migrating a codebase and don't want to touch the working part (JS) specify the loader on the import:
import MySVG from '-!svg-react-loader!src/assets/images/name.svg'

Then just use it as a JSX tag:

function f() {   return (<MySVG />); }