无法使用create-react-app导入图像 [英] cannot import image with create-react-app
问题描述
我正在使用 create-react-app
,并且正在加载图片。我正在按照此处,但我一直看到以下错误:
I'm using create-react-app
, and I am struggling to load images. I am following the instructions as specified here, but I keep seeing the following error:
Failed to compile.
Error in ./src/components/Home/imageIndex.ts
(1,24): error TS2307: Cannot find module './party.png'
有人知道为什么我运行 yarn start
时为什么我的应用程序继续失败
Does anyone know why when I run yarn start
my app continues to fail to compile?
我有一个 Home
组件,这就是我导入文件的方式:
I have a Home
component and this is how I am importing the file:
import photo from './party.png';
该组件位于 src / components / Home / index.tsx
,png文件位于 src / components / Home / party.png
。
The component is located in src/components/Home/index.tsx
and the png file is located in src/components/Home/party.png
.
这是我的package.json:
here is my package.json:
{
"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"
}
}
推荐答案
您确定您拥有正确的路径吗?同样,当您通过css导入图像时(如您在示例中所做的那样),您需要提供相对于公用文件夹而不是src文件夹的路径。我已经多次遇到这个问题。
Are you sure you've got the correct path? Also when you import an image via css (as is done in the example you mentioned) you need to give a path relative to the public folder and not the src folder. I have run into this problem several times.
使用import的示例:
An example using import:
import Image from './img.png'
...
// react example
...
render() {
return (
<img src={Image}/> // notice the curly
...
<img src="Image"/>
这篇关于无法使用create-react-app导入图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!