Resolving TypeScript error when importing images statically in Next.js

In order to enhance the performance of images in my nextjs app, I am working on image optimization. However, I encountered an issue stating: Cannot find module '/images/homeBg.jpg' or its corresponding type declarations.

The image is actually stored in public/images/name.jpg.

import { Layout } from '@common';
import Trips from '@ui/Trips/Trips';
import Image from 'next/image';
import bgImage from '/images/homeBg.jpg';
const HomePage = () => {
  return (
    <div className="relative h-screen w-full">
      <Image
        src={bgImage}
        fill
        className="-z-10 object-cover"
        alt="backgound_image_for_home_page"
      />
      <div className="mx-auto flex h-full w-full max-w-[2000px] flex-col space-y-10 px-7 py-36 lg:px-14">
        <h3 className="text-3xl font-normal leading-10 tracking-wider text-white lg:text-4xl">
          Welcome back, <br /> <span className="font-bold">Nedim!</span>
        </h3>
        <Trips />
      </div>
    </div>
  );
};

export default HomePage;

HomePage.layout = Layout;

Answer №1

When you start your Next.JS app in development mode, it generates a file called next-env.d.ts at the project's root and some type-definition files in the .next/types folder to ensure type safety.

Be sure to run the development command npm run dev at least once to see any changes.

You can also explicitly import next-env.d.ts in your tsconfig file if needed.

{
  "include": [
    "**/*.ts",
    "**/*.tsx",
    "next-env.d.ts",
    ".next/types/**/*.ts"
  ],
  ...  
}

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

Looking to incorporate an additional column 'LastName' that can be used for filtering in the Angular data table code. This column will be included if it is present in the data

function applyFilter(filterValue: string) { filterValue = filterValue.toLowerCase(); --- return filtered result return this.dataSet.filter( (item: any) => item.name ? item.name.toLowerCase(). ...

How can I use TailwindCSS in NextJS to remove the "gap" className from a component?

Currently, I am working on button components in NextJS with Tailwindcss and I am encountering a problem with some variants. Everything works fine, except when I remove the children (button text), I notice something strange that I can't quite figure ou ...

I encountered an unhandled rejection error of type TypeError when trying to read properties from an undefined value, specifically when attempting to read '__emotion_real'

I encountered an issue while developing a next js application: unhandledrejection typeerror: cannot read properties of undefined (reading '__emotion_real') This problem arose after I updated the next js and emotion libraries: "@emotion/bab ...

React Hook Form is flagging missing dependencies in the useEffect function

Before posting this question, I made an effort to search for a solution on Google. However, I am puzzled by the warning that the linter is giving me regarding my code. The warning message reads: ./components/blocks/Contact.tsx 119:6 Warning: React Hook us ...

Return the subclass from the constructor function

class X{ constructor(input: string) { // do things } f() {console.log("X")} } class Y extends X{ constructor(input: string) { // do things } f() {console.log("Y")} } class Z extends X{ con ...

The function switchMap does not exist in this context

After completing the Angular Tour of Heroes tutorial and some others, I decided to start building apps with Angular 2. One important thing I learned is that when we're listening for changes with a Subject, it's good practice to wait for a few sec ...

What is the best way to list the choices associated with a specific category?

The Node.js package I'm currently working with requires an argument of a specific type, which I can see is defined through a TypeScript declaration as follows: export declare type ArgType = 'A' | 'B' | 'C'; I am interes ...

Adding a method to an object with TypeScript: A step-by-step guide

In my current scenario, I am faced with a challenge where I need to test a function with a specific use of this. However, typescript poses constraints by either disallowing me from adding the method to the object, or if I define it as any, then my interfac ...

The dimensions of my Angular app have begun to unexpectedly expand

Currently in the process of developing an Angular application, I've encountered a frustrating issue. Each time I refresh the app using ng serve, the loading time seems to increase gradually. It can now take up to 10 seconds for changes to reflect in t ...

Error 504: GATEWAY_TIMEOUT - Vercel hosting running NextJS

I've encountered a frustrating issue with Vercel and NextJS that's causing me some headaches. My NextJS application has simple api routes, but when I try to access my hello world endpoint (or any other endpoint), I'm faced with the following ...

What is the best way to pass the modal dialog parameter sent from HTML to the TypeScript page?

I have implemented a dialog window using Angular where it opens by passing a parameter in the HTML side along with a transaction. To further enhance the functionality of my page, I want to incorporate the fab button. However, I am facing a challenge in sen ...

Can one utilize generic parameter value within a conditional type result field in Typescript?

Trying to create a versatile function type for data transformation can be a bit tricky. When dealing with a single object, it's straightforward: export type SingleObjFunction<InputDataType, OutputDataType> = (object: InputDataType) => Outpu ...

Updating the request body in Next 13 with middleware.ts: A step-by-step guide

I am looking for a way to modify the request body in NEXT 13 using a middleware function: import { NextRequest, NextResponse } from 'next/server'; enum MiddlewareRoutes { ACCESS = '/api/access', } const middlewareHandler = async ( ...

What is the reason behind receiving a 401 unauthorized error during the login process?

Currently, I am utilizing the NextAuth.js credentials provider for managing the login process. While attempting to log in, I have implemented error handling using a try-catch block to set the appropriate error state; however, I haven't incorporated di ...

Exploring the process of importing and exporting modules in TypeScript with the help of systemjs

Is there a way to export a module using systemjs in TypeScript? I encountered the error: TS1148 cannot compile modules unless the '--module' flag is provided. Here's my code; animal.ts export class Animal { color: string; age: numb ...

The use of fs.writeFileSync is invalid and will not work for this operation

Encountering an issue while working with fs in next.js, receiving the following error message: TypeError: fs.writeFileSync is not a function Here's a snippet from my package.json: resolve: { fallback: { "fs": false }, } ...

Tips for dealing with strong reference cycles in TypeScript?

I have created a tree-like structure in my implementation, consisting of parent and child objects. The parents contain a list of children while the children have references to their parents, facilitating easy navigation through the tree. I am now contempla ...

Is it possible to change a react-query query dynamically on the fly?

I am working on a next.js project that involves react-query. My goal is to showcase all the countries from the API on the homepage, along with functionalities to search by name and region using an input field and select dropdown. How can I dynamically chan ...

I'm curious as to why my t() texts are not updating in localhost/en after using i18n.changeLanguage(), but are refreshing correctly in localhost/fr

Hello There I recently created a website with dark mode and multi-language support for testing purposes, but I encountered an issue along the way. The Problematic Code I have removed any unnecessary elements from the code snippet below: portfolio/src/pag ...

I encountered an issue with adding a console log in the getStaticProps() function that resulted in the error: SyntaxError: Invalid Unicode escape sequence at eval (<anonymous>

Welcome to my users.js page! import React from 'react' const displayUsers = ({users}) => { return ( <> { users.map(user => { return <div key={user.id}> {user.name} </div> }) } </&g ...