February 23, 2021
As of the date I am writing this, Storybook will break on any component that renders an Image component from next/image.
That kind of sucks, but that's alright. We can stub out the implementation of next/image
with a mock in the meantime.
Example stub implementation for next/image
1// file: ./mocks/next/image.js23// Stub implementation of next/image. May need to be adapted depending on how you use next/image45import { createElement } from "react";67const Image = ({8 children,9 className,10 objectFit,11 objectPosition,12 src,13 style,14 ...restProps15}) => {16 return createElement(17 "img",18 {19 className,20 src,21 style: {22 ...style,23 objectFit,24 objectPosition25 },26 ...restProps27 },28 children29 );30};3132export default Image;
/ Example webpack config for storybook, using the next/image mock /
1// .storybook/main.js23const path = require("path");4const webpack = require("webpack");56module.exports = {7 /* ... */8 webpackFinal: (config) => {9 /**10 * !HACK11 * @description next/image doesn't work with storybook, so we are stubbing it with a mock12 * @author David Lee13 * @date February 23, 202114 */15 config.plugins.push(16 new webpack.NormalModuleReplacementPlugin(17 /^next\/image$/,18 path.resolve(__dirname, "./mocks/next/image.js")19 )20 );2122 return config;23 }24};
Now, you can generate snapshots, visually test, make demos, etc. of your components that make use of next/image
!
Happy coding! -- David Lee