One extra step after configuring @svgr/webpack in TypeScript projects
Learn to fix SVG import issues in TypeScript with @svgr/webpack by creating a declaration file for accurate type handling.This article was written when the SVGR documentation didn’t cover the TypeScript setup. Since then, the documentation has been updated to cover the setup, which is equivalent to the content covered below.
Problem
You may have followed the steps in the documentation and thought you were done setting @svgr/webpack
. But when you try to import an SVG file, you may encounter the following error.
Or if you are doing so in a Next.js project, you may find that the imported component is in any
type.
Cause
This is because TypeScript has no idea what the type *.svg
should become when it is imported into TS files. It is never being instructed or informed. And this is exactly what we are going to do.
Solution
-
Create a declaration file. It can be in any name and in any folder, but for the sake of this example, let's name it
src/types/image.d.ts
. -
Declare the type of the import.
If you are doing this in a Next.js project, change the 2nd
declare module
statement to the following.This is because Next.js has a different way of handling static images, which we are not going to cover in details here.
-
Instruct TypeScript to include
image.d.ts
when compilingIf you are doing so in a Next.js project, make sure the added statement goes BEFORE
next-env.d.ts
. This is because Next.js by default declared that importing from*.svg
should returnany
. We need to make sure our declaration overrides Next.js'.