Question

I can't reference an image in Next.js

I have a React component that's being used in Next.js page:

/pages/index.js

import React from 'react';
import ReactDOM from 'react-dom';
import Layout from "../src/hoc/Layout/Layout";
import Main from "../src/components/Main/Main";

const Index = () => (
   <Layout>
       <Main />
   </Layout>
);
export default Index

In Main.js I have the following code

import macbookIphone from '../../assets/images/mac-iphone.jpg';

I get the following error

Module parse failed: Unexpected character '�' (1:0) You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders (Source code omitted for this binary file)

I tried doing the following

In next-config.js

const withImages = require('next-images')
module.exports = withImages()

I'm still getting the same error.

What am I doing wrong?

 46  164294  46
1 Jan 1970

Solution

 48

From Next.js v11 onwards, you can do what you were doing without any additional config:

import macbookIphone from '../../assets/images/mac-iphone.jpg';

<Image src={macbookIphone} />

// or

<img src={macbookIphone.src} />

Ref: next/image

For earlier versions if you wish to import images instead of putting them in public directory, then you can configure file-loader or url-loader.

2021-07-20

Solution

 38

/public/favicon/mail.png

=> "/favicon/mail.png" will work

2021-01-19