Unable to import image using create-react-app

I am using create-react-app and I am trying my best to upload images. I follow the instructions given here , but I see the following error:

 Failed to compile. Error in ./src/components/Home/imageIndex.ts (1,24): error TS2307: Cannot find module './party.png' 

Does anyone know why when starting yarn start my application continues to compile?

I have a Home component, and that is how I import the file:

 import photo from './party.png'; 

The component is in src/components/Home/index.tsx , and the png file is in src/components/Home/party.png .

here is my .json package:

 { "name": "eai-reactjs-typescript-redux-starter", "description": "A ReactJS/TypeScript + Redux starter template with a detailed README describing how to use these technologies together and constructive code comments.", "version": "0.1.0", "private": true, "dependencies": { "react": "^15.6.1", "react-dom": "^15.6.1", "react-redux": "^5.0.5", "redux": "^3.7.0", "redux-logger": "^3.0.6" }, "devDependencies": { "@types/enzyme": "^2.8.0", "@types/jest": "^19.2.3", "@types/node": "^7.0.18", "@types/react": "^15.0.24", "@types/react-dom": "^15.5.0", "@types/react-redux": "^4.4.40", "@types/redux-logger": "^3.0.0", "enzyme": "^2.8.2", "react-addons-test-utils": "^15.5.1", "react-scripts-ts": "1.4.0", "redux-devtools-extension": "^2.13.2" }, "scripts": { "start": "react-scripts-ts start", "build": "react-scripts-ts build", "test": "react-scripts-ts test --env=jsdom", "eject": "react-scripts-ts eject" } } 
+5
source share
2 answers

Are you sure you have the right path? Also, when importing an image via css (as is done in the example you mentioned), you need to specify the path relative to the shared folder, not the src folder. I have come across this problem several times.

Import usage example:

 import Image from './img.png' ... // react example ... render() { return ( <img src={Image}/> // notice the curly ... 

but not

 <img src="Image"/> 
+6
source

I had the same problem and was able to solve it with the require statement.

const photo = require('./party.png');

and then in your component use for example:

render() { return ( <img src={photo}/>

also see this post Static Image Display with React, Typescript and Webpack

+4
source

Source: https://habr.com/ru/post/1268934/


All Articles