so I this is the first project I will be using Webpack for, I have scaled through this far by troubleshooting and copying codes in the docs In the hero section of my project, the images were dynamically added (via javascript). Here is the code
// Import multiple images
function importAll(r) {
let images = {};
r.keys().map(item => { images[item.replace('./', '')] = r(item) })
return images;
}
const images = importAll(require.context("./img/hero", true, /\.(png|jpe?g|svg)$/));
It is placed in index.html and required in the hero-js file thus:
const images = require('./index');
And implemented using this code:
// Set dynamic background
function setBg() {
console.log(' I am Working')
let today = new Date()
// let today = new Date(),
hour = today.getHours();
// Randomize bg
// morning
let morningArray = ['sunset-view-of-mountains-733100.jpg', 'purple-petal-flower-surrounded-by-green-plants-during-66288.jpg', 'time-lapse-photography-of-waterfalls-during-sunset-210186.jpg', 'two-cargo-ships-sailing-near-city-2144905.jpg'];
let morningBg = morningArray[Math.floor(Math.random() * morningArray.length)];
let morningPath = '../src/img/hero/';
let morning = morningPath + morningBg
console.log(morning)
// afternoon
let afternoonArray = ['empty-dining-tables-and-chairs-1579739.jpg', 'brown-and-green-mountain-view-photo-842711.jpg', 'photo-of-keyboard-near-mouse-3184460.jpg', 'america-arid-bushes-california-221148.jpg'];
let afternoonBg = afternoonArray[Math.floor(Math.random() * afternoonArray.length)];
let afternoonPath = '../src/img/hero/';
let afternoon = afternoonPath + afternoonBg;
// evening
let eveningArray = ['twisted-building-during-nighttime-1470405 s.jpg', 'beautiful-beauty-blue-bright-414612.jpg', 'landscape-photo-of-mountain-with-polar-lights-1434608.jpg', 'photo-of-toronto-cityscape-at-night-2478248.jpg'];
let eveningBg = eveningArray[Math.floor(Math.random() * eveningArray.length)];
let eveningPath = './src/img/hero/';
let evening = eveningPath + eveningBg;
// Show bg
//morning
if (hour < 12) {
hero.style.background = `url(${morning}) no-repeat center center / cover`;
greetingJs.textContent = 'Hi Good Morning,'
// afternoon
} else if (hour < 18) {
hero.style.background = `url(${afternoon}) no-repeat center center / cover`;
greetingJs.textContent = 'Hi Good Afternoon,'
}
// evening and night
else {
hero.style.background = `url(${evening}) no-repeat center center / cover`;
greetingJs.textContent = 'Hi Good Evening,'
}
}
On Netlify these images do not appear, only the fallback bg-colour saves the day.
After troubleshooting endlessly, I realize some interesting things going on in the network tabs of chrome dev tools:
The image seems to be requested in the wrong format and is pointing to nav.js which has nothing to do with it (its codes are in index.js and dynamicHero.js).
Also:
The error seems to be caused by a line in the nav.js file, which is otherwise working fine.
Also, I noticed that sometimes, the images aren't even being requested, hence no error is detected.
I did a little change in my netlify build settings too (and then it started requesting it)
At first, the Base directory was empty
And Publish directory was just dist.
Finally, my project structure looks like this
And my webpack config is:
//require plugins
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
// const MiniCssExtractPlugin = require('mini-css-extract-plugin');
// const { CleanWebpackPlugin } = require('clean-webpack-plugin');
// modules
module.exports = {
mode: 'development',
entry: {
app: './src/index.js',
},
devServer: {
},
module: {
rules: [
// babel
{
test: /\.js$/,
exclude: /node_modules/,
use: 'babel-loader'
},
{
test: /\.html$/,
use: [
{
// load with html loader and then minimize
loader: 'html-loader',
options: {
attrs: ['img:src', 'link:href'],
minimize: true,
interpolate: true,
}
}
]
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {
esModule: false,
},
}
],
},
]
},
plugins: [
/* new CleanWebpackPlugin({
cleanAfterEveryBuildPatterns: ['dist']
}), */
new HtmlWebpackPlugin({
template: './src/index.html',
filename: './index.html',
}),
/* new MiniCssExtractPlugin({
filename: '[name].css',
chunkFilename: '[id].css',
ignoreOrder: false,
}) */
],
optimization: {
splitChunks: {
chunks: 'all',
},
},
output: {
filename: '[name].bundle.js',
path: path.join(__dirname, 'dist'),
publicPath: '/'
},
}
Here is a link to my latest deploy preview on netlify: netlify
And a link to my repo, in case you would want to reproduce it: github
What am I doing wrong?