rob*_*rob 16 typescript reactjs webpack 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'
Run Code Online (Sandbox Code Playgroud)
有谁知道为什么当我运行yarn start我的应用程序时仍然无法编译?
我有一个Home组件,这就是我导入文件的方式:
import photo from './party.png';
Run Code Online (Sandbox Code Playgroud)
该组件位于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"
}
}
Run Code Online (Sandbox Code Playgroud)
arc*_*ryx 25
你确定你有正确的道路吗?此外,当您通过css导入图像时(如您提到的示例中所示),您需要提供相对于公用文件夹而不是src文件夹的路径.我已多次遇到这个问题.
使用import的示例:
import Image from './img.png'
...
// react example
...
render() {
return (
<img src={Image}/> // notice the curly
...
Run Code Online (Sandbox Code Playgroud)
并不是
<img src="Image"/>
Run Code Online (Sandbox Code Playgroud)
mel*_*ist 11
我有同样的问题,并能够用require语句解决.
const photo = require('./party.png');
然后在你的组件中使用如下:
render() {
return (
<img src={photo}/>
另请参阅此文章使用React,Typescript和Webpack显示静态图像