reactjstypescriptnext.jsnext-images

How to use PNG images in Next.js outside the default PUBLIC directory?


I saw that an alternative to be able to use images using another directory other than the Public folder, is to use the Next-Images library, but I do all the setup correctly as described in the documentation, I've seen several videos on the internet, but nothing works, I can only load it svgs. I'm using typescript in my project. There's a detail that I noticed regarding typing, which we have to add this reference:

/// <reference types="next-images" />

getting like this:

/// <reference types="next" />
/// <reference types="next/types/global" />
/// <reference types="next/image-types/global" />
/// <reference types="next-images" />

To the next-env.d.ts file, however every time I run the yarn dev command that reference that was added is automatically deleted.

My next.config.js file:

const withImages = require('next-images');

module.exports = withImages({
   inlineImageLimit: false,
   esModule:true,
});

Another thing I noticed is that: when the project is compiled, by the browser console the tag <img src="">, in the src is the path:

/_next/static/images/cora-c562c6fa203473521a5dc5b15a841192.jpg

Since there's this other path that your I manually put through the browser console, it works:

/_next/static/image/src/assets/cora.e76cddfc04ca9d4b8a3868b2c40e3b7f.jpg

So, if anyone knows if I'm missing any settings that I might not have done, or a video that might help, or a detail from the documentation, I'll be grateful.

Next Version: 11.0.1 Typescript Version: 4.3.5 Next-Images Version: 1.8.1


Solution

  • In your tsconfig.json, add next-env.d.ts to exclude array:

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

    Create a new file custom.d.ts and add this:

    /// <reference types="next" />
    /// <reference types="next/types/global" />
    /// <reference types="next-images" />
    

    In next.config.json:

    const withImages = require('next-images');
    
    module.exports = withImages({
      images: {
        disableStaticImages: true,
      },
    });
    

    Note that using next-images is not required for your use case at all. Next.js now supports this out of the box. So with default configuration (a fresh create-next-app), you can directly do:

    import Image from 'next/image';
    import img from '../path/to/img.png';
    
    <Image src={img} alt="some text"/>
    
    // or with img tag:
    
    <img src={img.src} height="100" width="100" alt="some text"/>
    

    Refer: Image Imports