I've built my first full React app, and it works beautifully. I load my dev-server and everything loads exactly as I would hope. Notably, my image files load perfectly.
An example of a successful image load on my dev server:
<img src='./img/sq/filename.jpg' />
When running the dev server, when I inspect this element in the console and go to 'Sources', I see the file tree like this:
- localhost:3333
- css [folder]
- js [folder]
- img/sq [folder]
- filename.jpg
- index [file]
This is as I would expect.
However, when running the production server, the image fails to load. When I inspect the element, and go to 'Sources', this is what I see instead:
- localhost:3000
- static [folder]
- css [folder]
- js [folder]
- index [file]
So my production build is apparently ignoring the /img/sq
folder altogether.
I've heard about file-loader and url-loader, but I've yet to find a clear and simple explanation of what they do and how to use them. I've installed both to my dependencies successfully, and I've added this loader to my webpack.config.js file:
{
test: /\.(jpe?g|png|gif|svg)$/i,
loaders: [
'file?hash=sha512&digest=hex&name=[hash].[ext]',
'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
]
}
After doing this, I'm not sure how this is supposed to change the way the images load. Should I change the way the image is referenced? Any help/pointers would be massively appreciated, as this has me stumped.
UPDATE:
This is my server.js file. I can't see any radical difference between the code that you posted and my own, except for me using res.render
method, to your res.sendFile
.
Is there anything I may have missed here?
server.js
var express = require('express')
var app = express();
app.use('/static', express.static(__dirname + '/static'));
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.get('*', function (req, res) {
res.render("index");
});
const port = process.env.PORT || 3000;
const env = process.env.NODE_ENV || 'production';
app.listen(port, err => {
if (err) {
return console.error(err);
}
console.info(`Server running on http://localhost:${port} [${env}]`);
});