[英]Large images not rendering with Webpack + React?
我正在尝试使用 Webpack 将图像文件夹中的图像渲染到 React 项目。 我注意到对于较小的照片(即物理上更小的尺寸,我想这意味着更小的文件大小),照片会加载。 但是,对于较大的照片,除了此处看到的占位符外,屏幕上不会呈现任何内容。 1
我怀疑这可能是由于 Webpack 配置不正确造成的。 照片导入和渲染本身正在工作,因为较小的照片会渲染。 具体来说,我怀疑这可能是 Webpack 中的“文件加载器”子句的问题。
下面是我的 Webpack 设置:
const webpack = require('webpack');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const config = {
entry: __dirname + '/imports/layouts/index.jsx',
output: {
path: __dirname + '/dist',
filename: 'bundle.js',
publicPath: '/',
},
resolve: {
extensions: [".js", ".jsx", ".css"]
},
plugins: [
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: "styles.css",
chunkFilename: "[id].css"
})
],
module: {
rules: [{
test: /\.jsx?/,
exclude: /node_modules/,
use: 'babel-loader'
},
{
test: /\.css$/,
use: [{
loader: MiniCssExtractPlugin.loader,
options: {
// you can specify a publicPath here
// by default it use publicPath in webpackOptions.output
publicPath: '../'
}
},
"css-loader",
"sass-loader"
]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: 'file-loader'
}
]
},
devServer: {
historyApiFallback: true,
},
module: {
rules: [{
test: /.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/
}, {
test: /\.css$/,
loader: "style-loader!css-loader"
}, {
test: /\.(jpe?g|jpg|png|gif|woff|woff2|eot|ttf|svg)(\?[a-z0-9=.]+)?$/,
loader: 'url-loader?limit=100000'
}]
},
};
module.exports = config;
如果它可能有用,下面是我在 React 中渲染图像的方式。
import photo from '../../images/sample_photo.jpg';
import './sample.css';
export default class Sample extends Component {
render () {
return (
<img src={photo}></img>
)
} }
由于某种原因,图像本身在浏览器中呈现为“24d565c81ae689a281aabb01ad3208db.jpg”,而不是“sample_photo.jpg”。
在您的 webpack 配置中,您已经定义了两次module
对象。
所以你的第二个module
配置将覆盖第一个。 由于您的第二个module
中未提及file-loader
,因此一旦您的url-loader
限制(100,000)超过文件将不会被解析。
此外,不建议将url-loader
用于较大的文件。
而是修改您的 webpack 配置以包含 url 和文件加载器。
像这样:
module: {
rules: [{
test: /.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/
}, {
test: /\.css$/,
loader: "style-loader!css-loader"
},
{
test: /\.(png|svg|jpg|gif)$/,
use: 'file-loader'
},
{
test: /\.(jpe?g|jpg|png|gif|woff|woff2|eot|ttf|svg)(\?[a-z0-9=.]+)?$/,
loader: 'url-loader?limit=100000'
}]
}
您的 url-loader 限制为 100k 字节或其他内容: limit=100000
尝试删除它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.