如何在React.js项目中加载图像(jpg)文件?我将图片保存在/src/images
中,文件名为iphone-template.jpg
。
webpack.config.js
const { resolve } = require('path');
const webpack = require('webpack');
module.exports = {
entry: [
'react-hot-loader/patch',
// activate HMR for React
'webpack-dev-server/client?http://localhost:8080',
// bundle the client for webpack-dev-server
// and connect to the provided endpoint
'webpack/hot/only-dev-server',
// bundle the client for hot reloading
// only- means to only hot reload for successful updates
'./index.js'
// the entry point of our app
],
output: {
filename: 'bundle.js',
// the output bundle
path: resolve(__dirname, 'docs'), // changed 'dist' to 'www'
publicPath: '/'
// necessary for HMR to know where to load the hot update chunks
},
context: resolve(__dirname, 'src'),
devtool: 'inline-source-map',
// devtool: "source-map"
devServer: {
hot: true,
// enable HMR on the server
contentBase: resolve(__dirname, 'docs'), // changed 'dist' to 'www'
// match the output path
publicPath: '/'
// match the output `publicPath`
},
module: {
rules: [
{
test: /\.js$/,
use: [ 'babel-loader'],
exclude: /node_modules/
},
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader'],
},
{
test: /\.(png|woff|woff2|eot|ttf|svg)$/,
loader: 'url-loader?limit=100000'
},
// the below webpack config was sourced from this,
// https://github.com/coryhouse/react-slingshot/issues/128
// in order to load favicon.
{
test: /\.jpe?g$|\.ico$|\.gif$|\.png$|\.svg$|\.woff$|\.ttf$|\.wav$|\.mp3$/,
loader: 'file-loader?name=[name].[ext]' // <-- retain original file name
},
{
test: /\.(png|jpg|)$/,
loader: 'file-loader?name=/images/[name].[ext]'
},
{
test: /\.(png|jpg|gif)$/,
loader: "file-loader?name=img/img-[hash:6].[ext]"
},
{
test: /\.(jpg|png|svg)$/,
loader: 'file',
include: './src/images'
}
],
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
// enable HMR globally
new webpack.NamedModulesPlugin(),
// prints more readable module names in the browser console on HMR updates
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
}),
],
};
App.js
import iPhone from '../images/iphone-template.jpg';
const App = (props) => {
return (
<div id="parent">
<NavBar {...navbar} />
{/* see scratchpad.txt for removed div. */}
<div id="iphone">
{/*<img src={iPhone} />*/}
<img className="iphone-template" src={iPhone} />
</div>
答案 0 :(得分:0)
如果它确实是webpack 2,则您需要在加载器的所有名称中使用file-loader
,因为它不再仅仅支持file
或url
来使用加载器。
除此之外,你有几个影响你的.jpg .png .gifs等。你可以摆脱重复,只为它们写一个,因为你所做的一切都是复制文件(没有优化,没有散列重命名),除非你想要你的根,你的图像和你的img目录在发行版中的副本
但问题是,您如何访问要显示的页面?