Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Bug]: Default stories show "Cannot find module [...]" with Storybook (v7) and Gatsby (v5) #21958

Open
oskari opened this issue Apr 6, 2023 · 11 comments

Comments

@oskari
Copy link

oskari commented Apr 6, 2023

Describe the bug

When setting up storybook v7 to a gatsby v5(?) project that uses custom babel config according to gatsby docs, default stories fail to show and instead show errors like:

Cannot find module './src/stories/Introduction.mdx'
webpackEmptyContext@http://localhost:59104/main.17f180ed.iframe.bundle.js:1:7557
_callee$/</<@http://localhost:59104/main.17f180ed.iframe.bundle.js:1:5140

or

Cannot find module './src/stories/Button.stories.ts'

webpackEmptyContext@http://localhost:59104/main.17f180ed.iframe.bundle.js:1:7557
_callee2$/</<@http://localhost:59104/main.17f180ed.iframe.bundle.js:1:5943

To Reproduce

git clone https://github.com/oskari/gatsby-v5-storybook-v7
npm run build-storybook && npx serve storybook-static

System

Environment Info:

  System:
    OS: macOS 13.2.1
    CPU: (10) arm64 Apple M1 Pro
  Binaries:
    Node: 18.14.1 - ~/.nvm/versions/node/v18.14.1/bin/node
    Yarn: 1.22.19 - /opt/homebrew/bin/yarn
    npm: 9.3.1 - ~/.nvm/versions/node/v18.14.1/bin/npm
  Browsers:
    Chrome: 111.0.5563.146
    Safari: 16.3
  npmPackages:
    @storybook/addon-essentials: ^7.0.2 => 7.0.2
    @storybook/addon-interactions: ^7.0.2 => 7.0.2
    @storybook/addon-links: ^7.0.2 => 7.0.2
    @storybook/blocks: ^7.0.2 => 7.0.2
    @storybook/react: ^7.0.2 => 7.0.2
    @storybook/react-webpack5: ^7.0.2 => 7.0.2
    @storybook/testing-library: ^0.0.14-next.2 => 0.0.14-next.2

Additional context

No response

@JerzyDamian
Copy link

Hello :) I have the same problem. We have upgraded Storybook to 7, followed all guides from docs and here: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#from-version-65x-to-700

And we have exactly the same error when storybook runs: Cannot find module './src/stories/Accordion.jsx'

@JerzyDamian
Copy link

I've tried to init clean Storybook with Gatsby 5 using "npx storybook@latest init" and there is the same error:
"Cannot find module './src/stories/Introduction.mdx'"

@tahunic
Copy link

tahunic commented Apr 23, 2023

Same issue here, is there any workaround?

@JerzyDamian
Copy link

JerzyDamian commented Apr 24, 2023

Same issue here, is there any workaround?

Workaround is to downgrade Storybook version to 6 and wait for update from Gatsby side

@smoothdvd
Copy link

smoothdvd commented Apr 30, 2023

pnpm with @tarojs has same issue.

@oskari
Copy link
Author

oskari commented May 23, 2023

Hey @shilman @JReinhold @jonniebigodes, I understand that Gatsby is not a priority on Storybook's radar and that you rely on community on fixing things, but it seems that nobody here has the slightest idea where to start with fixing this. Is it a problem with SB? is it a Gatsby problem? As far as I can understand, it's mostly with configuring webpack and that something changed between SB 6 -> 7. It seems that storybook's only public gatsby project failed to update too, looking at the commits on this branch .

Can you give any suggestions on where to start looking? It's a bit hard to figure out how things should be, when pretty much out-of-box it just doesn't work.

@graysonhicks
Copy link

Gatsby team would like this to work. It does seem confirmed the issue was introduced on the Storybook side with v7, not the Gatsby side with its v5. I see the new Framework API but its not clear if any previous framework without a plugin will be broken?

The main changes I see as possible culprits in the v6 -> v7 migration guide are the framework field and the stories field being made mandatory.

@krzy789
Copy link

krzy789 commented Jun 29, 2023

is there any update here?

@Danpan13
Copy link

Danpan13 commented Aug 7, 2023

this helped me resolve issue #22796

@oskari
Copy link
Author

oskari commented Aug 21, 2023

Despite the solutions offered, I am still unable to get this running.

First I'm running npx storybook@latest init on a fresh branch of my Gatsby v5 project (5.10.0). This will install storybook@7.3.2. Almost at the end I get this error when it tries to run storybook:

Running Storybook

> project-name@0.1.0 storybook
> storybook dev -p 6006 --initial-path=/onboarding --quiet

@storybook/cli v7.3.2

info => Starting manager..
info Addon-docs: using MDX2
info => Using implicit CSS loaders
info => Using default Webpack5 setup
<i> [webpack-dev-middleware] wait until bundle finished
node:internal/process/promises:288
            triggerUncaughtException(err, true /* fromPromise */);
            ^

Error: [BABEL]: --- PLACEHOLDER PACKAGE ---
This @babel/plugin-proposal-private-property-in-object version is not meant to
be imported. Something is importing
@babel/plugin-proposal-private-property-in-object without declaring it in its
dependencies (or devDependencies) in the package.json file.
Add "@babel/plugin-proposal-private-property-in-object" to your devDependencies
to work around this error. This will make this message go away.
 (While processing: /Users/oskari/projektit/project-name/node_modules/@babel/plugin-proposal-private-property-in-object/lib/index.js)
    at Object.<anonymous> (/Users/oskari/projektit/project-name/node_modules/@babel/plugin-proposal-private-property-in-object/lib/index.js:28:7)
    at Module._compile (node:internal/modules/cjs/loader:1254:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1308:10)
    at Object.newLoader (/Users/oskari/projektit/project-name/node_modules/esbuild-register/dist/node.js:2262:9)
    at extensions..js (/Users/oskari/projektit/project-name/node_modules/esbuild-register/dist/node.js:4807:24)
    at Module.load (node:internal/modules/cjs/loader:1117:32)
    at Module._load (node:internal/modules/cjs/loader:958:12)
    at Module.require (node:internal/modules/cjs/loader:1141:19)
    at require (node:internal/modules/cjs/helpers:110:18)
    at startHiding - secret - don't use this - v1 (/Users/oskari/projektit/project-name/node_modules/@babel/core/lib/errors/rewrite-stack-trace.js:55:12)

At this point I haven't been able to make any modifications to main.js or so, so I kinda expected something to go wrong. I check what the package in question is:

oskari:project-name/ (feature/storybook-v7✗) $ npm ls @babel/plugin-proposal-private-property-in-object                                                                                                                                                                             
project-name@0.1.0 /Users/oskari/projektit/project-name
└─┬ babel-preset-gatsby@3.10.0
  └─┬ @babel/preset-env@7.22.10
    └── @babel/plugin-proposal-private-property-in-object@7.21.0-placeholder-for-preset-env.2

and I add it to devDependencies.

I change my main.js to be:


const config: StorybookConfig = {
  stories: ['../src/**/*.mdx', '../src/**/*.stories.@(js|jsx|mjs|ts|tsx)'],
  addons: [
    '@storybook/addon-links',
    '@storybook/addon-essentials',
    '@storybook/addon-onboarding',
    '@storybook/addon-interactions',
  ],
  framework: {
    name: '@storybook/react-webpack5',
    options: {},
  },
  docs: {
    autodocs: 'tag',
  },
  webpackFinal: async config => {
    // Transpile Gatsby module because Gatsby includes un-transpiled ES6 code.
    config.module.rules[2].exclude = [
      /node_modules\/(?!(gatsby|gatsby-script)\/)/,
    ]

    // Remove core-js to prevent issues with Storybook
    config.module.rules[2].exclude = [/core-js/]
    // Use babel-plugin-remove-graphql-queries to remove static queries from components when rendering in storybook
    config.module.rules[2].use[0].options.plugins.push(
      require.resolve('babel-plugin-remove-graphql-queries')
    )
    config.resolve.mainFields = ['browser', 'module', 'main']
    return config
  },
}

export default config

and preview.ts to:

import type { Preview } from '@storybook/react'

import { action } from '@storybook/addon-actions'

// Gatsby's Link overrides:
// Gatsby Link calls the `enqueue` & `hovering` methods on the global variable ___loader.
// This global object isn't set in storybook context, requiring you to override it to empty functions (no-op),
// so Gatsby Link doesn't throw errors.
global.___loader = {
  enqueue: () => {},
  hovering: () => {},
}
// This global variable prevents the "__BASE_PATH__ is not defined" error inside Storybook.
global.__BASE_PATH__ = '/'

// Navigating through a gatsby app using gatsby-link or any other gatsby component will use the `___navigate` method.
// In Storybook, it makes more sense to log an action than doing an actual navigate. Check out the actions addon docs for more info: https://storybook.js.org/docs/react/essentials/actions

window.___navigate = pathname => {
  action('NavigateTo:')(pathname)
}

const preview: Preview = {
  parameters: {
    actions: { argTypesRegex: '^on[A-Z].*' },
    controls: {
      matchers: {
        color: /(background|color)$/i,
        date: /Date$/,
      },
    },
  },
}

export default preview

Running the failed command again:

@storybook/cli v7.3.2

info => Starting manager..
info Addon-docs: using MDX2
info => Using implicit CSS loaders
info => Using default Webpack5 setup
<i> [webpack-dev-middleware] wait until bundle finished
[BABEL] Note: The code generator has deoptimised the styling of /Users/oskari/projektit/project-name/node_modules/react-dom/cjs/react-dom.development.js as it exceeds the max of 500KB.
[BABEL] Note: The code generator has deoptimised the styling of /Users/oskari/projektit/project-name/node_modules/@storybook/components/dist/formatter-6736J7QO.mjs as it exceeds the max of 500KB.
<i> [webpack-dev-middleware] wait until bundle finished: /runtime~main.iframe.bundle.js
<i> [webpack-dev-middleware] wait until bundle finished: /vendors-node_modules_storybook_addon-actions_dist_index_js-node_modules_storybook_addon-essen-5effb3.iframe.bundle.js
<i> [webpack-dev-middleware] wait until bundle finished: /main.iframe.bundle.js

and this time storybook does start but opening any of the example stories results in huge delay while it's building and the end result is always:
image

Am I missing something here?
I still believe the problem is with gatsby projects using custom babel config, which is pretty normal use-case. My .babelrc config is following:

{
  "presets": [
    [
      "babel-preset-gatsby",
      {
        "reactRuntime": "automatic"
        //"reactImportSource": "@emotion/react"
      }
    ],
    ["@babel/preset-env", { "targets": { "node": "current" } }],
    "@babel/preset-typescript"
  ],
  "plugins": [
    "@babel/plugin-proposal-private-property-in-object",
    "@babel/plugin-proposal-class-properties",
    "@babel/plugin-proposal-private-methods"
  ],
  "env": {
    "development": {
      "compact": false
    }
  }
}

@jeron-diovis
Copy link

@oskari I ran into same issue of "Cannot find module...", with storybook@7.6.17, and managed to solve it.

Don't know how it was back in 7.3.2, but currently babel-loader is at index 3 in rules array, not 2. Check it out, maybe you're just updating a wrong rule.

Also in your listing, you do this:

    // Transpile Gatsby module because Gatsby includes un-transpiled ES6 code.
    config.module.rules[2].exclude = [
      /node_modules\/(?!(gatsby|gatsby-script)\/)/,
    ]

    // Remove core-js to prevent issues with Storybook
    config.module.rules[2].exclude = [/core-js/]

Looks like the second expression overrides the first one. So you don't actually add the regexp for gatsby modules.


Another arcane nuance I found is that you're not allowed to replace the exclude option with a new value.
Although Webpack allows to assign there whatever you want (string / regexp / func / array) – but here, it MUST be an array and it MUST preserve whatever else is already in there – despite that besides /node_modules/ it only contains paths to some generic config files, which aren't even exist in my project.

Violating this will actually cause the "Cannot find module..." error.

Meaning:

// this won't  work:
loader.exclude = /node_modules\/(?!(gatsby|gatsby-script)\/)/
// this also won't work:
loader.exclude = [
  /node_modules\/(?!(gatsby|gatsby-script)\/)/
]
// this worked for me:
loader.exclude[0] = /node_modules\/(?!(gatsby|gatsby-script)\/)/

Overall, to switch from SWC to Babel in my setup, I had to do following:

  1. Add @babel/preset-typescript – either to babelrc, or to babel hook in main.ts, doesn't matter.
    Without it storybook won't handle import type expressions and other TS syntax.

  2. Update exclude option for babel-loader.
    To don't mess with cryptic indexes, I organized it like this:

webpackFinal: config => {
  type Rule = {
    use?: Array<string | { loader: string }>
    exclude?: Array<string | RegExp>
  }
  const babelLoader = (config.module?.rules as Rule[])?.find(rule =>
    rule.use?.some(use =>
      (typeof use === 'string' ? use : use.loader).includes('/babel-loader/')
    )
  )
  if (babelLoader?.exclude) {
    babelLoader.exclude[0] = /node_modules\/(?!gatsby|gatsby-script)/
  }
  return config
}
  1. Idk why is that, but with all above I got these errors:
ERROR in ./node_modules/@storybook/test/dist/index.js 6:69019-69032
Module not found: Error: Can't resolve 'os' in '/path/to/node_modules/@storybook/test/dist'

ERROR in ./node_modules/@storybook/test/dist/index.js 6:69037-69051
Module not found: Error: Can't resolve 'tty' in '/path/to/node_modules/@storybook/test/dist'

So in webpackFinal I also added this:

Object.assign(config.resolve.fallback, { os: false, tty: false })

And with that, it finally worked.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests