ค้นหาเว็บไซต์

reactjs - ไม่สามารถนำเข้าภาพด้วย create-react-app


ฉันกำลังใช้ create-react-app และฉันกำลังประสบปัญหาในการโหลดภาพ ฉันได้ทำตามคำแนะนำตามที่ระบุไว้ที่นี่ แต่ฉันยังคงเห็นข้อผิดพลาดดังต่อไปนี้:

Failed to compile.

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

มีใครรู้ไหมว่าทำไมเมื่อฉันรัน yarn start แอปของฉันยังคงคอมไพล์ไม่สำเร็จ?

ฉันมีคอมโพเนนต์ Home และนี่คือวิธีที่ฉันกำลังนำเข้าไฟล์:

import photo from './party.png';

คอมโพเนนต์อยู่ใน src/components/Home/index.tsx และไฟล์ png อยู่ใน src/components/Home/party.png

นี่คือไฟล์ 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"
  }
}

คำตอบ #1

คุณแน่ใจหรือว่าคุณมีเส้นทางที่ถูกต้อง? นอกจากนี้เมื่อคุณนำเข้าภาพผ่าน CSS (เช่นเดียวกับในตัวอย่างที่คุณกล่าวถึง) คุณจำเป็นต้องให้เส้นทางที่สัมพันธ์กับโฟลเดอร์ public ไม่ใช่โฟลเดอร์ src ฉันเจอปัญหานี้หลายครั้งแล้ว

ตัวอย่างการใช้งาน import:

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

และไม่

<img src="Image"/>

คำตอบ #2

ฉันมีปัญหาแบบเดียวกันและสามารถแก้ไขได้ด้วยคำสั่ง require

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

และจากนั้นในคอมโพเนนต์ของคุณให้ใช้มันแบบนี้:

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

ดูโพสต์นี้ด้วย การแสดงภาพนิ่งโดยใช้ React, Typescript และ Webpack

บทความที่เกี่ยวข้อง