所以我只想在我的React应用程序中使用一些图像,但是图像没有加载。某些图像在CSS中是这样设置的:
background-image: url('/../img/logo.png');
我想在React组件内部使用图像的另一种方式 img标签,我该怎么做?
这是我的webpack配置:
const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = (env) => {
const isProduction = env === 'production';
return {
entry: './src/app.js',
output: {
path: path.resolve(__dirname, 'public', 'dist'),
filename: 'bundle.js'
},
module: {
rules: [{
loader: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
}, {
test: /\.s?css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
// you can specify a publicPath here
// by default it use publicPath in webpackOptions.output
publicPath: '../'
}
},
{
loader: 'css-loader',
options: {
sourceMap: true
}
},
{
loader: 'sass-loader',
options: {
sourceMap: true
}
}
]
}]
},
plugins: [
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: "styles.css",
})
],
devtool: isProduction ? 'source-map' : 'inline-source-map',
devServer: {
contentBase: path.resolve(__dirname, 'public'),
historyApiFallback: true,
publicPath: '/dist/'
},
performance: {
hints: process.env.NODE_ENV === 'production' ? "warning" : false
},
}
};
index.html放在公用文件夹中:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Kinnisvara ABC</title>
<link rel="stylesheet" href="/dist/styles.css" type="text/css">
</head>
<body>
<div id="app"></div>
<script src="/dist/bundle.js"></script>
</body>
</html>
CSS正在加载,但图像未加载。
有人可以帮我吗?
答案 0 :(得分:0)
您没有添加像CSS这样的图片加载器,因此请尝试添加
test: /\.(gif|jpe?g|png)$/,
答案 1 :(得分:0)
有2种方式
使用webpack网址加载器 将此行添加到webpack文件中的rules模块
{测试:/.(png|jpg|woff|woff2|eot|ttf|svg|gif)$/,加载程序:“ url-loader?limit = 1024000'}
使用服务指向图片
答案 2 :(得分:0)
{
test: /\.(gif|png)$/, //Customise according to your need
use: [
{
loader: 'url-loader',
options: {
limit: 10000,
name: PATH + '.[ext]' //Path will be assets or image path
}
}
]
}
像这样在Webpack配置中配置 url-loader 。