How to import or require images in Next.js?

Published October 25, 2020

To import images in a Next.js project you can install a plugin called next-images which helps in doing all the heavy lifting for us.

yarn add -D next-images

Or

npm i --save-dev next-images

Then you have to add this to the Next.js config file.

If you haven't created a Next.js config file, you should create it at the root of your project directory and should have the name next.config.js.

After that, you need to import the next-images package in the next.config.js file.

// require next-images package
const nextImages = require("next-images");

Then you need to export the module from the next.config.js file like this,

// require next-images package
const nextImages = require("next-images");

// export the module
module.exports = nextImages();

If you want to customize the next-images package, you need to pass those options as an object to the package. Visit next-images options to see the available options.

// require next-images package
const nextImages = require("next-images");

// export the module
module.exports = nextImages({
  // options
  esModule: true,
});

That's all for the configuration part 🌟.

Now you can simply require the images from any of the Next.js pages or components using the require() function and pass a valid path to the image source like this,

// require your image
const MyImageComponent = () => <img src={require("../public/myImage.jpg")} />;

If you are using the next-compose-plugins to combine several plugins you can pass the next-images as an array to the next-compose-plugins package like this,

// next-compose-plugins package
const withPlugins = require("next-compose-plugins");
// require next-images package
const nextImages = require("next-images");

module.exports = withPlugins([
  [
    nextImages,
    {
      // pass any options to the next-images package
    },
  ],
]);

Feel free to share if you found this useful 😃.


Share on: Facebook Twitter