使用 webpack 加载本地图片
Loading local images with webpack
你好我正在尝试使用 webpack 加载本地图像,它编译成功但是我收到以下错误(并且没有图像)
GET 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}>
你的问题实际上是你错过了输出的 publicPath
:
output: {
path: path.resolve(__dirname, 'public/scripts'),
filename: 'bundle.js',
publicPath: '/scripts/'
},
devServer: {
contentBase: path.resolve(__dirname, 'public'),
publicPath: '/scripts/'
},
输出的 属性 publicPath 必须与 devServer 上的 publicPath 匹配。
你好我正在尝试使用 webpack 加载本地图像,它编译成功但是我收到以下错误(并且没有图像)
GET 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}>
你的问题实际上是你错过了输出的 publicPath
:
output: {
path: path.resolve(__dirname, 'public/scripts'),
filename: 'bundle.js',
publicPath: '/scripts/'
},
devServer: {
contentBase: path.resolve(__dirname, 'public'),
publicPath: '/scripts/'
},
输出的 属性 publicPath 必须与 devServer 上的 publicPath 匹配。