Reputation: 769
I'm trying to import an image from an url in storybook. In nextJS, images can't come from a domain unless you allow it.
I allowed it in the next-config.js
file doing the following:
module.exports = {
env: {
API: process.env.API
},
images: {
domains: ['https://sourceexample.com/image']
}
};
It works for when making pages outside of storybook, with the regular next dev
. However, when I try to render the same page that has this component:
<Image
alt="example"
src="https://sourceexample.com/image.png"
width="auto"
height="auto"
/>
It shows the exact same error when I didn't add the allowed domain in next-config.js
, which is:
Invalid src prop (https://sourceexample.com/image.png) on `next/image`, hostname "source" is not configured under images in your `next.config.js
I thought that maybe it was because I should import next-config.js
into storybook configurations, so I google for it and stumbled upon this piece of code, which I don't know what to do with it. This code is written under "How do I setup Storybook to share Webpack configuration with Next.js?" in the storyboook documentation.
module.exports = {
webpackFinal: async (baseConfig) => {
const nextConfig = require('/path/to/next.config.js');
// merge whatever from nextConfig into the webpack config storybook will use
return { ...baseConfig };
},
I tried making a spread of the properties in nextConfig
like adding
return {...baseConfig, ...nextConfig}
in the return method. It didn't work. Can someone explain what is happening here and how am I supposed to use it?
Upvotes: 5
Views: 4834
Reputation: 166
Just add this code to the .storybook/preview.js
file:
import * as nextImage from 'next/image';
Object.defineProperty(nextImage, 'default', {
configurable: true,
value: props => <img {...props} />
});
Update: seems that this addon fixes the issue - https://storybook.js.org/addons/storybook-addon-next
Upvotes: 9
Reputation: 71
I ran into this issue and solved it by mocking 'next/image' in storybook's webpack config (see details at the link below)
https://storybook.js.org/docs/react/workflows/build-pages-with-storybook#mocking-imports
Create a new React component file:
// file: .storybook/__mocks__/NextJSImageMock.js
import React from "react";
export default function NextImageMock(props) {
return <img {...props} />;
}
Then, overwrite the import:
// file: .storybook/webpack.config.js
module.exports = ({ config }) => {
config.resolve.alias = {
"next/image": require.resolve("./__mocks__/NextJSImageMock.js"),
};
return config;
};
Upvotes: 2