2017-06-17 115 views
4

我使用create-react-app,我很努力加載圖像。我下面的說明爲指定here,但我總是看到以下錯誤:無法導入圖像與創建反應應用程序

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" 
    } 
} 

回答

5

你確定你有正確的路徑?另外,當你通過css導入一個圖像(就像你剛纔提到的例子中所做的那樣),你需要給出一個相對於公用文件夾而不是src文件夾的路徑。我已經多次遇到這個問題。

使用進口的一個例子:

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

,而不是

<img src="Image"/> 
相關問題