Failed to import svg files in typescript

In typescript(*.tsx) files typescript(*.tsx) I cannot import an 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 the .js file, I can import it without any problems with the exact same import operation. I believe this has something to do with the type of svg file that needs to be set up somehow for ts transpiler.

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

+7
svg typescript
source share
2 answers

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

Create a file called custom.d.ts with the following contents:

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

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

+12
source share

Thanks to smarx for pointing out the use of require() . Therefore, in my case, it should be:

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

which works fine in * .tsx files

+7
source share

All Articles