0

I've been building out a web application using Typescript & React and during local development I wanted to display a local jpeg as a default user profile image. I received this import error when trying to use the image directly: Cannot find module '../assets/default_profile.png' or its corresponding type declarations.

The component file:

import styled from "styled-components";
import img from '../assets/default_profile.png'

const ProfileImage = styled.div`
  background-image: url(img);
  background-size: cover;
  background-position: center;
  border-radius: 50%;
  width: 100px;
  height: 100px;
`;

const ProfilePhoto = () => {
  return <ProfileImage />;
};

export default ProfilePhoto;

This whole thing led me down a rabbit hole of SO. This one recommended adding the .d.ts declaration file and then altering the tsconfig.json file: Importing images in TypeScript React - "Cannot find module"

That didn't work for me.

This article recommended npm installing file-loader and then altering the webpack config.

I didn't want to go messing with the webpack config since that seems like it will be it's own can of worms and in this SO post it was mentioned it is generally better to not eject the webpack config that is generated with create-react-app.

So I guess what I am trying to do here is tie all these similar posts together and get some consensus.

What is my best course of action? Do I need to npm run eject and modify my webpack config? Is there an easier way? Should I even be trying to display an image that is locally on my machine (e.g. is there 3rd party hosting that would just be easier to point to a url?)?

Appreciate any help in advance!

Jacob Garwin
  • 55
  • 1
  • 9

1 Answers1

0

Look at this repo, I made the repo for your issue