Configure next/image Component to be Unoptimized

Michael Chan
InstructorMichael Chan

Share this video with your friends

Send Tweet
Published 8 months ago
Updated 6 months ago

In this lesson, we configure next/image for use in Storybook. next/image is a Next.js component that creates highly performance-optimized images to users based on device capability and browser dimensions. It can be unoptimized for compatibility in development environments like Storybook.

Michael Chan: [0:01] Out of the box, Storybook doesn't know how to deliver images that use next/image. If we look at the story, we see that this Vercel SVG isn't being presented. That's because next/image does a lot of optimization work behind the scenes.

[0:15] Because we haven't told Storybook where Next public asset directory is, let's start by telling Next how to find public assets. For that, we'll open up our package.json and make two changes, both to the storybook and build-storybook commands. In both cases, we want to serve the Next public directory. In the storybook script, we'll use a relative path, but in build-storybook, we'll just use public.

[0:42] Both of these changes only take place when we run these commands, so we need to stop our Storybook server. Before we start it again, let's make our other change. We want to change the way that next/image works, but only in the context of Storybook.

[0:55] To do that, we open up our config in .storybook and open the preview.js file, which governs every story. Here we'll do a little bit of magic on next/image component. First, we import * as NextImage from "next/image".

[1:15] Next, we create an intermediate variable called OriginalNextImage, and assign it NextImage.default export. Finally, we rewrite NextImage using Objects.defineProperty. On NextImage, we want to redefine the default.

[1:37] We put two changes, configurable: true, and value of a component, which takes props turns OriginalNextImage, all those props spread on it with an additional prop of unoptimized. Save that. Restart our Storybook server. The command yarn storybook.

[2:03] Now, still using next/image to deliver this SVG, see it appear in our storybook without affecting the next config at all.