Unable to import svg files in typescript

In typescript(*.tsx) files I cannot import svg file with this statement:

import logo from './logo.svg';

Transpiler says:[ts] cannot find module './logo.svg'. My svg file is just <svg>...</svg>.

But in .js file I'm able to import it without any issues with exact the same import statement. I suppose it has something to do with type of svg file which must be set somehow for ts transpiler.

Could you please share how to make this work in ts files?


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


  • If you're using create-react-app 2+: docs

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 />); 
}