Storybook can't find module '@reach/router'. But gatsby is working fine

Viewed 217

Getting the error

Storybook can't find module '@reach/router'. Gatsby is working fine.

import * as React from "react";

import { useLocation } from "@reach/router";



const Header = () => {

    const { pathname } = useLocation();
    const isCheckoutHeader = pathname.includes("quote-process");
    return (
        <>
         <div>code here</div>
       </>
    );
};

export default Header;
2 Answers

With Gatsby v4 you'll need to remap @reach/router to @gatsbyjs/reach-router. If using Storybook v6 and Webpack5 you can use the NormalModuleReplacementPlugin to perform this remapping.

This assumes your setup is similar to the one explained in the Gatsby docs: Visual Testing with Storybook.

// .storybook/main.js
const webpack = require("webpack")

module.exports = {
  stories: ["../src/**/*.stories.mdx", "../src/**/*.stories.@(js|jsx|ts|tsx)"],
  addons: [
    "@storybook/addon-links",
    "@storybook/addon-essentials",
    "@storybook/addon-interactions",
  ],
  framework: "@storybook/react",
  core: {
    builder: "@storybook/builder-webpack5",
  },
  staticDirs: ["../public", "../static"],
  webpackFinal: async config => {
    // Transpile Gatsby module because Gatsby includes un-transpiled ES6 code.
    config.module.rules[0].exclude = [/node_modules\/(?!(gatsby)\/)/]
    // Use babel-plugin-remove-graphql-queries to remove static queries from components when rendering in storybook
    config.module.rules[0].use[0].options.plugins.push(
      require.resolve("babel-plugin-remove-graphql-queries"),
    )
    // remap @reach/router to fork included in Gatsby
    config.plugins.push(
      new webpack.NormalModuleReplacementPlugin(
        /^@reach\/router/,
        "@gatsbyjs/reach-router",
      ),
    )
    return config
  },
}

This is because the purpose of Storybook is made to see the components and not for routing between the pages.

Related