【发布时间】:2020-07-25 15:24:04
【问题描述】:
我正在尝试使用 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”。
【问题讨论】:
标签: javascript html css reactjs webpack