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

What's the deal with the Zod getter function?

Is it possible to create a getter function within a Zod object? For instance, in ES5 you can achieve the following: const person = { firstName: "John", lastName: "Doe", get fullName() {return `${this.firstName} ${this.lastName}`} } person.fullNam ...

A guide on automatically focusing on a Material UI Formik form TextField using React and TypeScript

I'm attempting to automatically focus my textField, but the 'autoFocus' attribute only seems to work after I submit the form and add a value. If no values are added (i.e. when opening the miui modal for the first time), the autoFocus does no ...

NextJS reliably accesses the request object on each page

I'm currently working on setting up an authentication system using express, passport, and nextjs with OpenID Connect. The user data is stored in the request object using express-session, providing access to req.user in each request. My challenge now ...

Guide on deploying a web application using Socket.io and SvelteKit on Vercel

Currently, I'm developing a multiplayer .io-style game that utilizes both Socket.io and SvelteKit. While testing the project on a local development server, everything runs smoothly. However, upon deploying to Vercel, an error message stating Failed to ...

Creating a ref with Typescript and styled-components: A comprehensive guide

Trying to include a ref into a React component looks like this: const Dashboard: React.FC = () => { const [headerHeight, setHeaderHeight] = useState(0); const headerRef = React.createRef<HTMLInputElement>(); useEffect(() => { // @ts ...

Converting a promise of type <any> to a promise of type <entity>: A beginner's guide

As a newcomer to TypeScript and NestJS, I am wondering how to convert Promise<any[]> to Promise<MyEntity[]> in order to successfully execute the following code: const usersfromTransaction = this.repoTransaction .createQueryBuilder() ...

The where clause in the Typeorm query builder instance is not functioning properly after its common usage

When fetching data for my relations, I opted to use QueryBuilder. In order to validate certain get request parameters before the index, I established a common QueryBuilder instance as shown below. // Common Get Query const result = await this.reserva ...

Can someone explain how to define "a type of object that must not be empty" in typescript?

I'm working with a function that can operate on any type T, but with the constraint that if T is an object, it cannot potentially be empty. Here's what I've tried: declare function myFunction<T>(param: T extends Record<string, neve ...

Accessing information from Next.js API endpoint in a Next.js web application

Currently, I am in the process of developing a web application using Next.js APP Router for both the frontend and backend components. The frontend takes care of rendering the user interface, while the backend comprises API routes. I require some guidance o ...

Receive the most recent query in a Nuxt plugin following the completion of page loading

So, here's the issue - I have a plugin containing some functions that are supposed to update URL queries. However, every time I run $global.changePage(2) or $global.changeLimit(2), the console.log(query) outputs an empty object and doesn't show t ...

Limit function parameter types to object keys

Is it possible to constrain my function parameter to match the keys of an object? I want to achieve something similar to this: export const details = { x: { INFO_x: 'xxx' }, y: { I ...

Tips for selecting content for rendering with GetServerSideProps

Is there a way to display different text before and after a specific time without revealing all the content in the HTML? I've attempted using if-else logic within the component, but it ends up exposing text that should be hidden. Can getServerSideProp ...

Failure of Styling Inheritance in Angular 2 Child Components from Parent Components

My Parent Component utilizes a Child Component. I have defined the necessary styles in the Parent CSS file, and these styles change appropriately when hovering over the div. However, the Child Component does not inherit the styling classes of the Parent Co ...

What is the process for removing a document with the 'where' function in Angular Fire?

var doc = this.afs.collection('/documents', ref => ref.where('docID', '==', docID)); After successfully retrieving the document requested by the user with the code above, I am unsure of how to proceed with deleting that do ...

There seems to be an issue with the OpenAPI generator for Angular as it is not generating the multipart form data endpoint correctly. By default

Here is the endpoint that needs to be addressed: @PostMapping(value = "/file-upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public List<FileReference> handleFileUpload( @RequestPart(value = "file", name = "f ...

`Is There a Solution When Compilation Fails?`

I keep encountering an issue when I run the command npm start. The problem seems to be originating from PancakeSwap Frontend and after several attempts, I am still unable to resolve it. Your assistance is greatly appreciated :) Below is a snippet of my Ap ...

Tips for transforming a string into a variable within an Angular framework

I'm working with a JSON object retrieved from an API let arr = [{"name": 'abc',"age": '23'},{"name": 'qwe',"age": '37'},{"name": 'wqewqe',"age&quo ...

Issue with using third-party package types in Angular library creation

My project involves creating a custom voice recognition library, and I have decided to utilize 3rd party package types called @types/dom-speech-recognition. However, upon attempting to integrate these types into my service, the compiler raised errors indic ...

React Native facing issues with Environment Variables

In my current project, I am using React Native Web alongside NextJS. This setup involves running components with React Native web within a monorepo and utilizing a single .env file to manage environment variables. While the env variables for NextJS are fu ...

typescript optimizing initial load time

When importing the npm package typescript, it typically takes around 0.3 seconds. Is this considered an acceptable load time? Are there any steps that can be taken to optimize performance? The code snippet in index.js demonstrates the process: import &apo ...