Reputation: 118
I'm using webpack for react.js but have problem to load static images. In my react components I try to load images from for example mainContainer.js file. I tried with file-loader and I think that I set it all correctly but still webpack simple doesn't recognize images folder.
Here's an inline link to Github.
Part from my .js component where I'm trying to load image:
<a href="/" className="author">
<span className="name">Jane Doe</span><img src="./images/avatar.jpg" alt="" />
</a>
and part of webpack config file:
module.exports = {
entry: './src/scripts/main.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
// publicPath: '/dist'
},
module: {
rules: [
{
test: /\.js$/,
use: [
{
loader: 'babel-loader',
options: {
presets: ['es2015']
}
}
]
},
{
test: /\.scss$/,
use: extractPlugin.extract({
use: ['css-loader', 'sass-loader']
})
},
{
test: /\.html$/,
use: ['html-loader']
},
{
test: /\.(jpg|png)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'images/',
publicPath: 'images/'
}
}
]
},
{
test: /\.woff($|\?)|\.woff2($|\?)|\.ttf($|\?)|\.eot($|\?)|\.svg($|\?)/,
use: 'url-loader'
}
]
},
plugins: [
extractPlugin,
new HtmlWebpackPlugin({
template: 'src/index.html'
})
// new CleanWebpackPlugin(['dist'])
]
};
Upvotes: 0
Views: 5822
Reputation: 16441
The way I do this is by using the CopyWebpackPlugin to copy all of my static images into the build folder. Then in my components I can reference them as if they exist at the root level:
const copy = new CopyWebpackPlugin([
{ from: ROOT + '/images', to: 'images' }
]);
In your component:
<img src="/images/logo.png" />
Upvotes: 1