嗨,我正在尝试使用webpack加载本地图像,它可以成功编译,但是出现以下错误(并且没有图像)
获取http://192.168.1.196:3000/b09d0fa90cacadcad6ce1679aea3d2ee.png 404(未找到)
这是我的webpack.config.js文件:
const path = require('path')
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'public/scripts'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['env']
}
}
},
{ test: /\.(png|jpg)$/, loader: 'url-loader?limit=8192' }
]
},
devServer: {
contentBase: path.resolve(__dirname, 'public'),
publicPath: '/scripts/'
},
devtool: 'source-map'
}
这是我导入图像的方式
import goku from '../public/images/goku.png'
我也在尝试在img中直接使用require来获得相同的结果。
<img src =${require('../public/images/goku.png')}>
<img src =${goku}>
答案 0 :(得分:1)
您的问题实际上是您在输出中错过了publicPath
:
output: {
path: path.resolve(__dirname, 'public/scripts'),
filename: 'bundle.js',
publicPath: '/scripts/'
},
devServer: {
contentBase: path.resolve(__dirname, 'public'),
publicPath: '/scripts/'
},
输出上的publicPath属性必须与devServer上的publicPath相匹配。