Diogo Neiss
Diogo Neiss

Reputation: 117

Cannot import image in NextJs project

I'm converting a previus React.js website to a Next.js one, followed the guide on converting create react-app to a next-app.

An image is imported for usage inside a html vanilla <img> tag, in order to use tailwind classes. Followed some tutorials on the matter and they advised installing next-images and configuring next.config.js with the following code

// next.config.js
const withImages = require('next-images')
module.exports = withImages({
 esModule: true
})

This is the error thrown at runtime

./components/partials/Features.js:3:0
Module not found: Can't resolve '/images/features-bg.png'
  1 | import React, { useState, useRef, useEffect } from 'react';
  2 | import Transition from '../utils/Transition.js';
> 3 | import FeaturesBg from '/images/features-bg.png';
  4 | import FeaturesElement from '/images/features-element.png'
  5 | import Image from 'next/image';
  6 |

The folder structure I'm using follows the create next-app example, with a public folder containing all static files. I created an images folder inside it and verified that there are no typos in the filename. Full repository is available here

Does anyone know what I'm doing wrong?

Upvotes: 2

Views: 4733

Answers (3)

Diogo Neiss
Diogo Neiss

Reputation: 117

Changed the import FeaturesBg from '/images/features-bg.png' to const FeaturesBg = '/images/features-bg.png' and nextjs relative /public static imports worked.

Upvotes: 3

Nikolai Kiselev
Nikolai Kiselev

Reputation: 6613

The specified path is incorrect. In your case it'd be ../../public/images/filename.png.

If you're not sure why you used next-images package, perhaps, you don't need it. Just add images to public and reference it as @m.hedayat suggested.

Upvotes: 0

mansoureh.hedayat
mansoureh.hedayat

Reputation: 645

In next js you should give the address of your image to src of img tag , you shouldn't import it , like this <img src="/images/features-element.png" alt="" />

Upvotes: -1

Related Questions