Reputation: 653
I've deployed my react application build in Webpack in netlify. I see the CSS, Fonts and everything else loading fine, but not the images under assets/images folder.
Here's my folder structure in live site source path:
my webpack.config.js:
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: ['./src/index.js', '@babel/polyfill'],
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-react', '@babel/preset-env'],
},
},
},
{
test: /\.css$/i,
exclude: /node_modules/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: true,
},
},
],
},
{
test: /\.(gif|png|jpe?g)$/,
use: [
{
loader: 'file-loader',
options: {
// name: '[name].[ext]',
// name: '[path][name].[hash].[ext]',
name: '/src/assets/images/[hash].[ext]',
// outputPath: 'src/assets/images/',
},
},
],
},
],
},
devServer: {
host: '192.168.1.10', //your ip address,
historyApiFallback: true,
contentBase: './build',
disableHostCheck: true,
},
resolve: {
extensions: ['*', '.js', '.jsx'],
},
output: {
path: path.resolve(__dirname, '/dist'),
filename: 'bundle.js',
publicPath: '/',
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new HtmlWebpackPlugin({
filename: 'index.html',
inject: true,
template: path.resolve(__dirname, 'index.html'),
}),
],
devServer: {
contentBase: './build',
hot: true,
},
};
And I try to access my images in JSX like this -
import { HeaderLogo } from '../../assets/images/image_name.png';
When I inspect element and change in path from /assets/images/image-name.png
to /src/assets/images/image-name.png
it is showing image in live site.
Here's my folder structure in local:
The same is working fine in local. Not sure what causing issue in prod. I know something is wrong with my file-loader path. But not sure where to correct.
Any suggestions please?
Upvotes: 4
Views: 6490
Reputation: 1849
You need to copy the image files to the build directory.
To do that, install webpack copy plugin: copy-webpack-plugin
npm install copy-webpack-plugin --save-dev
And webpack config should be:
// import copy plugin
const CopyPlugin = require('copy-webpack-plugin');
module.exports = {
entry: ['./src/index.js', '@babel/polyfill'],
module: {
...
},
plugins: [
...
new CopyPlugin({
patterns: [
{
from: path.resolve(__dirname, '/src/assets/images'),
to: path.resolve(__dirname, 'dist')
}
]
}),
]
};
For more details https://www.npmjs.com/package/copy-webpack-plugin
Upvotes: 4