How to add path aliases for images in TypeScript?

Viewed 220

I have configured paths in tsconfig.json. Everything works fine except importing asset files like svg and png.

Here is my paths in tsconfig.json

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@components/*": ["./src/components/*"],
      "@components": ["./src/components"],
      "@app/*": ["./src/app/*"],
      "static": ["static/*"]
    },
    ...
}

Here how I import:

import imageAdd from "static/images/image-add.png";
import circleIcon from "static/icons/circle-close.svg"
2 Answers

Replace "static": ["static/*"] with "static/*": ["static/*"]

Finally, solved. Need to add some d.ts file. Eg. images.d.ts with content:

declare module "*.png";
declare module "*.jpg";

After go to tsconfig.json file and add this file to include:

  "include": ["images.d.ts", <other includes>]

Probably, you'll need to install file-loader. I use gatsby, so I didn't need to configure anything

Related