react.js - webpack+react 本地调试时图片无法加载
本文介绍了react.js - webpack+react 本地调试时图片无法加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
我的webpack配置
// ...
entry: {
index: './src/root.js'
},
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/'
}
// ...
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: 'img/[name].[hash:7].[ext]'
}
}
html 使用相对路径
<img src='../../static/imgs/logo.png' alt='icon'></img>
服务器代码
// ...
var app = express()
var compiler = webpack(config)
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true,
publicPath: config.output.publicPath
}))
app.use(require('webpack-hot-middleware')(compiler))
app.listen(3000, function(err) {
if (err) {
console.log(err)
return
}
console.log('Listening at http://localhost:3000')
})
问题是图片无法加载,请问一下我图片引用的路径应该怎么写
我html改成这种写法:
const logo = require('../../static/imgs/logo.png')
<img src={logo} alt='icon'></img>
就提示缺少file-loader,这样的原因又是为什么,和上面的引用方式那种比较好
解决方案
使用第二种方式加载,在webpack中加上file-loader的配置就可以了,网上一搜就会。
用第一种方式的话要写绝对路径,相对路径webpack会认为是一个普通字符串,不做处理,在编译后就无法找到图片的地址了。
这篇关于react.js - webpack+react 本地调试时图片无法加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文