【发布时间】:2020-11-07 16:04:05
【问题描述】:
我开始在我的 React 应用程序中使用 webpack 来捆绑图像,但它们没有显示在浏览器中(有一个 <img/> 标签,但没有图像)。如果我运行“webpack”,公共文件夹中存在带有散列名称的图像,如果我运行“webpack-dev-server”,它还显示图像已捆绑,但浏览器中仍然没有。
这是我的 webpack 配置文件:
module.exports = (env) => {
const isProduction = env === 'production';
const CSSExtract = new ExtractTextPlugin('styles.css');
return {
entry: ['babel-polyfill', './src/app.js'],
output: {
path: path.resolve(__dirname, './public/scripts'),
filename: 'bundle.js'
},
module: {
rules: [{
loader: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
},
{
test: /\.(png|jp(e*)g|svg)$/,
use: [{
loader: 'url-loader',
options: {
limit: 8000, // Convert images < 8kb to base64 strings
name: 'images/[hash]-[name].[ext]'
}
}]
},
{
test: /\.s?css$/,
use: CSSExtract.extract({
use : [
{
loader : 'css-loader',
options : {
sourceMap : true // source map for css in development
}
},
{
loader : 'sass-loader',
options : {
sourceMap : true
}
},
{
loader: "jshint-loader"
}
]
})
},
]
},
plugins : [
CSSExtract,
],
devtool: isProduction ? 'source-map' : 'cheap-eval-source-map', // source map for locating a bug in source files, not in the bundle
devServer: {
contentBase: path.join(__dirname, "public"),
publicPath: "/scripts/",
historyApiFallback: true // this line is for client-side routing
},
}
}
这就是我将图像添加到我的应用程序的方式:
import img1 from '../../assets/img/ticket.jpg';
这就是我在render() 方法中使用它的方式。
<img src={img1}/>
我在浏览器开发工具中看到了这个,但图像本身没有显示:
<img src="images/9011429377e91d003e5b64251ac3b9a8-ticket.jpg">
如何修复它并显示图像?
【问题讨论】:
-
您找到解决方案了吗?我有类似的问题 - 我认为
标签: webpack webpack-file-loader