outputs of gingervitis

Images with optimization work now!

As you may have noticed, I finally got optimized images working!
In a previous post, I was having a difficult time working with next-optimzed-images, with respect to paths.
The problems that I had were both a little dumb (on my part), and quite confusing.
All off their docs tell us to just do something like:
<img src={require('./images/my-image.jpg')} />
I had assumed ./images/ was the one located in /public/images, because that's where all these blog post images were coming from, as the NextJS docs had suggested. So I could not understand why I was getting Cannot find module.. errors.
Turns out a) src="{string path}" vs src=require({string path}) are obviously different. And b) the ./images path is actually relative to the JS file requiring it.
So on that note, I tried to create the path relative to where public was. But that didn't work.
I moved the images folder outside of public to the root level and it worked. Ok I've read that Next's pubilc folder was special. Ok fine.
Now that I realized these things, I started optimizing my code to account for this pathing.
That's when I found out..

require() seems really picky.

require() likes this:
const imgFull = require(`../../images/${src}`);
It does not like this:
const IMAGE_PATH = '../../images';
const imgFull = require(`${IMAGE_PATH}/${src}`);
It's like the same thing isn't it?! But nooo, this one keeps resulting in my dreaded
Server Error
Error: Cannot find module '../../images/my-image.png'
I really doesn't make sense to me. My guess is that it has to do with weird timing of when it reads constants and when it reads require()s during build time. 🤷🏻‍♀️

Getting everything else to work so far

So I took some ideas from this article to get me started.
I found out how react-markdown could read my markdown blog posts and convert the images to optimizable ones.
I'm also using react-syntax-highlighter to make these code blocks display!
Another thing I learned out of this article was adjusting this webpack conifg. I decided to rename my root image folder post-images.. At the time I felt unreasonably weird about just calling it /images at the root level. In order to make that work, I also have to edit the next.config.js file like this:
// next.config.js

const path = require("path");
webpack(config) {
  config.resolve.alias.images = path.join(__dirname, "post-images");
  return config;
Ok that's all the learnings for now.
Until next time!
#nextjs#web development