I'm encountering a ModuleNotFoundError that says: "Module not found: Error: Can't resolve". What could be causing this

I have encountered an issue while trying to create a blog post page on my NextJS website. The page displays correctly on my local machine, but when I deploy it to production, I am facing the following error and I am unsure of how to resolve it: Here is the error:

ModuleNotFoundError: Module not found: Error: Can't resolve '../../public/images/posts/our-new-home/shelly-crying.jpg' in '/vercel/path0/pages/posts'
17:10:01.443    > Build error occurred
17:10:01.443    Error: > Build failed because of webpack errors
17:10:01.444        at /vercel/path0/node_modules/next/dist/build/index.js:17:924
17:10:01.444        at runMicrotasks (<anonymous>)
17:10:01.444        at processTicksAndRejections (internal/process/task_queues.js:95:5)
17:10:01.444        at async Span.traceAsyncFn (/vercel/path0/node_modules/next/dist/telemetry/trace/trace.js:6:584)
17:10:01.459    Error: Command "npm run build" exited with 1

Below is the structure of my project: https://i.stack.imgur.com/lSeGQ.png

Also included is the content of my post our-new-home.tsx:

import React, { ReactElement } from "react";
import ShellyCrying from "../../public/images/posts/our-new-home/shelly-crying.jpg";
import NewTruck from "../../public/images/posts/our-new-home/new-truck.jpg";
import TrailerSold from "../../public/images/posts/our-new-home/trailer-sold.jpg";
import MessyLivingRoom from "../../public/images/posts/our-new-home/messy-living-room.jpg";
import MovingDay from "../../public/images/posts/our-new-home/snow-moving.jpg";
import LumpySleeping from "../../public/images/posts/our-new-home/lumpy-sleeping.jpg";
import CatalinaComforter from "../../public/images/posts/our-new-home/catalina-comforter.jpg";
import ShellyLumpy from "../../public/images/posts/our-new-home/shelly-lumpy.jpg";

export default function ourNewHome(): ReactElement {
  return (
    <div className="mx-auto max-w-2xl p-4 md:p-0">
      <title>Our New Home</title>
      <article>
        <h1 className="text-5xl mb-4">Our New Home</h1>
        <p className="my-4">
          We are excited to share our next adventure! We both work remotely now,
          so we decided to take this opportunity to not be confined to a one
          bedroom, one bathroom insanely expensive apartment anymore. This was
          our chance to do something a bit non-traditional and we dove head
          first into researching how to make this happen before our lease was up
          in mid-April.
        </p>
        <h2 className="text-2xl font-semibold">Step 1: The Essentials</h2>
        <p className="my-4">
          We quickly realized that we needed to decide what was essential to us
          in a home on wheels. We also had to decide what was better for us –
          something we could tow or something we could drive. These things were
          fairly easy to hash out. With my upbringing from an aeronautical
          engineer and bookkeeper and being married to a petroleum
          engineer/chemist, we did the only thing one can do – make a million
          Excel spread sheets! We are happily married and would like to continue
          to be for many years to come, so we decided we needed to have enough
          space to not be on top of each other. Other necessities - a bed that
          didn’t need to be folded up every day in order to have room to walk
          around, a bathroom with a door (some things need to be kept private,
          am I right!), work space, storage, a spot for a litter box, and a
          fully functioning kitchen. Bryan is a great cook and we wanted to be
          able to maintain our lifestyle of cooking most of our meals, having
          room to meal prep, and having a fridge that could hold a week’s worth
          of food. As for what led us to end up purchasing a travel trailer,
          there were a few things. One – price. We weren’t looking to spend
          hundreds of thousands of dollars on an RV, especially since we didn’t
          know if this lifestyle was going to be sustainable for us. Two –
          practicality of getting around. We knew that with our lifestyle it
          would be easier to drop our trailer and then explore, without worrying
          about where to park a 40+ foot recreational vehicle. Three – previous
          experiences. Bryan’s dad, Steve, had many RVs and there always seemed
          to be something wrong with the engine. We didn’t want to risk having
          the engine die and be in the shop for months. An RV in the shop isn’t
          that bad when you don’t live it in full time, but when it is your
          home, that would really put a damper on things. Given the popularity
          of traveling since COVID, it has become increasingly difficult to get
          parts and service. So maybe we were jaded, because of Steve, but we
          like to think that he was proud of us for learning from his life
          lessons.
        </p>
        ... (content continues)
        
      </article>
    </div>
  );
}

Answer №1

Response credited to @juliomalves(visit their comments section): statically serving files in the public directory

I updated all the src= attributes to point to static references like this:

<img src="/images/shelly-crying.jpg" />

This modification allowed for a successful production build.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for adding a border to a table cell without disrupting the overall structure of the table

Looking for a way to dynamically apply borders to cells in my ng table without messing up the alignment. I've tried adjusting cell width, but what I really want is to keep the cells' sizes intact while adding an inner border. Here's the sim ...

Error encountered while attempting to retrieve backend information. Kindly verify the compatible server-side rendering (SSR)

After making the switch from Data Store to GraphQL in my code, my builds are now failing. I have a CI/CD setup in Amplify that triggers a build when I check in code. The only changes I made were related to adding references to amplify/api: import { API } f ...

Modifying elements in an array using iteration in typescript

I'm trying to figure out how to iterate over an array in TypeScript and modify the iterator if necessary. The TypeScript logic I have so far looks like this: for (let list_item of list) { if (list_item matches condition) { modify(list_ite ...

The dilemma with NextJS Image parameters

We're currently using NextJs image to load images and it's been functioning smoothly. However, we've encountered an issue with the generation of image URLs like the one below https://example.com/_next/image?url=/static/icons/Callus.svg& ...

The argument labeled as 'shop' does not fit the criteria for the parameter 'items' or 'cart'

I've been doing some research but haven't had any luck finding a solution. I'm fairly new to Angular and currently working on a webstore project. I followed a tutorial, but encountered an error along the way. import { select, Store } from & ...

Troubleshooting font color issues with PrimeNG charts in Angular

I have a chart and I am looking to modify the color of the labels The gray labels on the chart need to be changed to white for better readability Here is my code snippet: HTML5: <div class="box-result"> <h5 class="title-resul ...

What is the best way to set up TypeScript interfaces using predefined string literals to limit the possible data types for shared attributes?

In this scenario, we have two interfaces named A and B with validation and variant properties. The goal is to create an Example object by using only the variant and validation values provided (since field is already defined). However, I encountered an erro ...

Is the variable empty outside of the subscribe block after it's been assigned?

Why is a variable assigned inside subscribe empty outside subscribe? I understand that subscribe is asynchronous, but I'm not sure how to use await to render this variable. Can someone please help me and provide an explanation? I am attempting to retr ...

Determining the height of dynamically rendered child elements in a React application

Looking for a way to dynamically adjust the heights of elements based on other element heights? Struggling with getting references to the "source" objects without ending up in an infinite loop? Here's what I've attempted so far. TimelineData cons ...

Error: Unexpected token '<' found while using Next.js middleware, causing a SyntaxError

I have implemented a Next.js middleware that redirects to the login page if there is no available token from the Spotify API. This is how my middleware looks: import { getToken } from "next-auth/jwt"; import { NextResponse } from "next/serv ...

Assigning roles on signup with Auth0 in NextJS: A step-by-step guide

Recently, I've been exploring the library called nextjs-auth0 (https://github.com/auth0/nextjs-auth0) and have been attempting to utilize the handleAuth hook to extract a query argument for specifying the user's role upon signing up. Here is an ...

getStaticProps will not return any data

I'm experiencing an issue with my getStaticProps where only one of the two db queries is returning correct data while the other returns null. What could be causing this problem? const Dash = (props) => { const config = props.config; useEffect(() ...

Is the Property Decorator failing to substitute the definition?

My code is similar to the following scenario, where I am attempting to replace a property based on a decorator export function DecorateMe() { return function(component: any, propertyKey: string) { Object.defineProperty(component, propertyKey, ...

Having issues with TypeScript custom commands in Cypress?

Update: https://github.com/cypress-io/cypress/issues/1065#issuecomment-351769720 Removing an import from my commands.ts fixed it. Thanks In the process of transitioning my cypress project to use TypeScript, I am following the guidelines provided at https: ...

Retrieving the path parameter in a Next.js APIabstractmethod

I need assistance with extracting information from the file routes/api/[slug]/[uid].ts Specifically, I am looking to retrieve the slug and uid within my handler function. Can anyone provide guidance on how to achieve this? ...

Transform Observable RxJS into practical results

In a straightforward scenario, I have an upload action on the page that looks like this: onUpload$: Subject<SomeUpload> = new Subject<SomeUpload>(); uploadAction$: Observable<Action> = this.onUpload$.map(entity => this.someActionServi ...

Creating dynamic pages with Next.js/Vercel can be quite sluggish

I am currently working with Next.js and hosting my project on Vercel. The website is powered by WordPress, which provides the data headlessly. Due to the large number of pages, I only generate a few during the build process (the first three for pagination) ...

Experience the power of Nextjs paired with Material UI and a personalized global stylesheet for

I am utilizing Next.js 9.3 with the export feature to produce a static site. The setup for Material UI follows this example implementation (https://github.com/mui-org/material-ui/tree/master/examples/nextjs). In addition to Material UI, I have a global st ...

What is the process for creating a nullable column in TypeORM?

Within my User entity, there is an optional column for the user's avatar image: @Entity() export class User { @PrimaryGeneratedColumn('uuid') id: string @Column({ unique: true }) email: string @Column({ unique: true }) ...

Create a package themed with Material UI for export

I am attempting to create a new npm package that exports all @material-ui/core components with my own theme. I am currently using TypeScript and Rollup, but encountering difficulties. Here is the code I have: index.ts export { Button } from '@materia ...