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

Storybook broken when no React import with new JSX transform from react > 16.14.0 #12881

Closed
xavier-villelegier opened this issue Oct 23, 2020 · 27 comments

Comments

@xavier-villelegier
Copy link

xavier-villelegier commented Oct 23, 2020

Describe the bug
React 16.14.0 introduced the new JSX transform, which means you don't have to import React when when you use JSX anymore. Sadly, I am not able to remove any import from the components/stories used in storybook. Did I miss something ? 🤔

To Reproduce
Steps to reproduce the behavior:

  1. Create a new React app npx create-react-app my-app && cd my-app
  2. Check that it's on React > 16.14 (should be)
  3. Add storybook npx sb init
  4. Run storybook npm run storybook
  5. Remove the import React from 'react' from the .stories.js or .js file of one component and go to the story of this component (you might need to disable the react/react-in-jsx-scope eslint rule)
  6. It breaks 💥 React is not defined

Expected behavior
A beautiful and shiny story ✨

Screenshots
image

System

Environment Info:

  System:
    OS: macOS 10.15.6
    CPU: (8) x64 Intel(R) Core(TM) i7-8557U CPU @ 1.70GHz
  Binaries:
    Node: 14.13.0 - ~/.nvm/versions/node/v14.13.0/bin/node
    Yarn: 1.22.4 - ~/.yarn/bin/yarn
    npm: 6.14.8 - ~/.nvm/versions/node/v14.13.0/bin/npm
  Browsers:
    Chrome: 86.0.4240.111
    Safari: 13.1.2
  npmPackages:
    @storybook/addon-actions: ^6.0.26 => 6.0.26
    @storybook/addon-essentials: ^6.0.26 => 6.0.26
    @storybook/addon-links: ^6.0.26 => 6.0.26
    @storybook/node-logger: ^6.0.26 => 6.0.26
    @storybook/preset-create-react-app: ^3.1.4 => 3.1.4
    @storybook/react: ^6.0.26 => 6.0.26

I also tried with storybook 6.1.0-alpha.28, same results

@RookY2K
Copy link

RookY2K commented Oct 23, 2020

Problem is with @storybook/react. It adds the @babel/preset-react preset without the requisite runtime: 'automatic' option set.

This worked for me:

// main.js
module.exports = {
  // ...
  babel: async (options) => ({
    ...options,
    presets: [
      ...options.presets,
      [
	'@babel/preset-react', {
	  runtime: 'automatic',
	},
        'preset-react-jsx-transform' // Can name this anything, just an arbitrary alias to avoid duplicate presets'
      ],
    ],
  }),
};

@shilman
Copy link
Member

shilman commented Oct 23, 2020

What are the implications of building this option into storybook? Would it be a breaking change?

@RookY2K
Copy link

RookY2K commented Oct 23, 2020

This depends on how React versions without the new jsx transforms would handle the 'automatic' runtime. I'd have to do some testing to figure that out. Don't have the time at the moment, but if no one else has confirmed this by the time I roll back around, I can check.

Edit I lied.. I took the few seconds required to downgrade my React version to 16.13.1 and the build failed with

Module not found: Error: Can't resolve 'react/jsx-runtime'

So it appears that this would be a breaking change unless you made it configurable and defaulted to the classic runtime.

@matamatanot
Copy link
Contributor

matamatanot commented Oct 24, 2020

Create React App, Next.js and Gatsby have already supported new JSX transform.

https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html#create-react-app

Here is a Next.js implementation example.

Auto enable React's new JSX transform on 17.x

vercel/next.js#16603

@shilman
Copy link
Member

shilman commented Oct 24, 2020

Looks like this is also breaking our CI on CRA4:

info => Modifying Create React App rules.
info => Using default Webpack setup.
info => Compiling preview..
ERR! => Failed to build the preview
ERR! 
ERR! src/App.js
ERR!   Line 6:5:    'React' must be in scope when using JSX  react/react-in-jsx-scope
ERR!   Line 7:7:    'React' must be in scope when using JSX  react/react-in-jsx-scope
ERR!   Line 8:9:    'React' must be in scope when using JSX  react/react-in-jsx-scope
ERR!   Line 9:9:    'React' must be in scope when using JSX  react/react-in-jsx-scope
ERR!   Line 10:16:  'React' must be in scope when using JSX  react/react-in-jsx-scope
ERR!   Line 12:9:   'React' must be in scope when using JSX  react/react-in-jsx-scope

https://app.circleci.com/pipelines/github/storybookjs/storybook/14162/workflows/7f23260d-a9ce-445b-92fd-c15fd98b97c7/jobs/269075

@RichardVoyles09
Copy link

RichardVoyles09 commented Oct 24, 2020 via email

@shilman
Copy link
Member

shilman commented Oct 26, 2020

Jeepers creepers!! I just released https://github.com/storybookjs/storybook/releases/tag/v6.1.0-alpha.30 containing PR #12899 that references this issue. Upgrade today to the @next NPM tag to try it out!

npx sb upgrade --prerelease

Closing this issue. Please re-open if you think there's still more to do.

@shilman shilman closed this as completed Oct 26, 2020
@shilman shilman reopened this Oct 26, 2020
@shilman
Copy link
Member

shilman commented Oct 26, 2020

NOTE: this is hopefully fixed in 6.1 ☝️ . We need to get it back into the stable release, but are having problems with repros in CI. In the meantime if people can upgrade to 6.1 to test it out, please give it a try and report back:

npx sb upgrade --prerelease

If it doesn't work right away, try removing & regenerating lockfiles.

@RookY2K
Copy link

RookY2K commented Oct 26, 2020

Upgrading to latest alpha fixed my issue. Will now patiently wait until the fix gets merged into the stable release.

Thanks!

@DiFuks
Copy link

DiFuks commented Oct 28, 2020

I have a similar problem in browser console:

ReferenceError: _jsx is not defined

My packages versions:

{
    "@storybook/addon-docs": "^6.1.0-alpha.31",
    "@storybook/react": "^6.1.0-alpha.31",
    "react": "^17.0.1",
    "react-dom": "^17.0.1"
}

main.js file:

module.exports = {
  stories: ['../src/components/**/*.stories.tsx'],
  addons: ['@storybook/addon-docs'],
  webpackFinal: (config) => {
    config.resolve.plugins.push(new TsconfigPathsPlugin());

    return config;
  }
};

This problem exists only after production build. No problem in "start-storybook" mode

Edit I removed @storybook/addon-docs from the list of addons and the error was removed. Apparently, the reason for the error in this addon

@NandoSangenetto
Copy link

NandoSangenetto commented Oct 29, 2020

I'm getting the same error that @DiFuks is getting, _jsx is not defined.

image

I've created a small repo where you can reproduce this bug: https://github.com/nandosangenetto/storybook-bug-repro

I've tried to remove all addons, as @DiFuks did, but it didn't work.

What is odd is that it works when I run npm run storybook (start-storybook -p 6006), but fails when I try to build it with npm run build-storybook (build-storybook).

@shilman
Copy link
Member

shilman commented Oct 29, 2020

@DiFuks are you also using styled components?

@shilman
Copy link
Member

shilman commented Oct 29, 2020

I've opened a separate issue for this @NandoSangenetto @DiFuks #12952

@DiFuks
Copy link

DiFuks commented Oct 30, 2020

@DiFuks are you also using styled components?

No, I don't use styled-components.

Also, I commented out the addons again. And the error hasn't gone away. So, the problem is @storybook/react

@sibelius
Copy link

fixed for us on v6.1.0-rc.0

@shilman
Copy link
Member

shilman commented Nov 13, 2020

I'm closing this and will follow up on #12952

@shilman shilman closed this as completed Nov 13, 2020
@Fernando-Marquardt
Copy link

Jeepers creepers!! I just released https://github.com/storybookjs/storybook/releases/tag/v6.1.0-alpha.30 containing PR #12899 that references this issue. Upgrade today to the @next NPM tag to try it out!

npx sb upgrade --prerelease

Closing this issue. Please re-open if you think there's still more to do.

This doesn't seems to work with Yarn 2. I am not getting the runtime: 'automatic', even with React 17 and react/jsx-runtime being present and that is probably because of the paths used may not be working with Yarn (Yarn 2 does not store files in node_modules but zipped in its .yarn/cache instead).

@iam-yan
Copy link

iam-yan commented Jan 30, 2021

@shilman
Is is fixed? I still have this issue with the following stack:
storybook:6.1.15,react:17.0.1,next:10.0.5,Yarn Berry, PnP

@shilman
Copy link
Member

shilman commented Jan 30, 2021

@gaetanmaisse any thoughts on yarn 2 compat?

@Xerkus
Copy link

Xerkus commented Feb 6, 2021

#12899 Added support for new JSX transform and it is included in 6.1 release, however implementation depends on file location with node_modules that prevents it from working with yarn pnp.

CRA uses resolve without specifying paths and it works.
https://github.com/facebook/create-react-app/blob/282c03f9525fdf8061ffa1ec50dce89296d916bd/packages/react-scripts/config/webpack.config.js#L79-L85

Is there something special in storybook setup?

@TeemuKoivisto
Copy link

For any sorry soul who wandered here to fix that pesky ModuleNotFoundError: Module not found: Error: Can't resolve 'react/jsx-runtime' error, in my case I was too unfamiliar with the storybook configuration that I didn't notice that it existed in a different spot, away from the root of the project where all the other webpack configs laid. So, heading to stories/config/webpack.config.js I finally found the config and added the alias:

  config.resolve.alias = {
    // react: require.resolve('react'),
    'react/jsx-runtime': require.resolve('react/jsx-runtime'),
    'react-dom': require.resolve('react-dom'),
    'react-hot-loader': require.resolve('react-hot-loader'),
    'styled-components': require.resolve('styled-components'),
  }

Which actually required me to comment out the react alias. I'm not quite sure why, but it seems to have conflicted with the jsx runtime. Interesting behavior, indeed. Hopefully it now works.

@toridyar
Copy link

For any sorry soul who wandered here to fix that pesky ModuleNotFoundError: Module not found: Error: Can't resolve 'react/jsx-runtime' error, in my case I was too unfamiliar with the storybook configuration that I didn't notice that it existed in a different spot, away from the root of the project where all the other webpack configs laid. So, heading to stories/config/webpack.config.js I finally found the config and added the alias:

  config.resolve.alias = {
    // react: require.resolve('react'),
    'react/jsx-runtime': require.resolve('react/jsx-runtime'),
    'react-dom': require.resolve('react-dom'),
    'react-hot-loader': require.resolve('react-hot-loader'),
    'styled-components': require.resolve('styled-components'),
  }

Which actually required me to comment out the react alias. I'm not quite sure why, but it seems to have conflicted with the jsx runtime. Interesting behavior, indeed. Hopefully it now works.

Thank you for this! I banging my head against a wall for 2 days with this issue and this was the resolution (commenting out the previously defined react alias when adding the alias for jxs-runtime)

@jam-awake
Copy link

I'm pretty sure the fix here was only for the Preview, not the Manager. I've written a custom addon that uses React in the Manager and ran into the same problem here.

@sigginjals
Copy link

sigginjals commented Feb 1, 2023

@jam-awake I'm having the same issue, did you find a solution?

@jam-awake
Copy link

@sigginjals Yeah. I needed to add runtime: "automatic" to React's preset option in the manager's webpack config:

modul.exports = {
  ...
  managerWebpack: (c) =>
     setReactRuntimeAutomatic(c),
};
  
const modifyConfigModuleRules = (fn) => (config) => {
  return {
    ...config,
    module: {
      ...config.module,
      rules: fn(config.module.rules),
    },
  };
};

const setReactRuntimeAutomatic = modifyConfigModuleRules((rules) => {
  return rules.reduce((acc, next) => {
    if (
      isNonNullObjectWithField(next, "use") &&
      isNonNullArray(next.use) &&
      next.use[0] &&
      isNonNullObjectWithField(next.use[0], "options") &&
      isNonNullObjectWithField(next.use[0].options, "presets")
    ) {
      const presets = next.use[0].options.presets;
      next.use[0].options.presets = presets.reduce((pAcc, pNext) => {
        if (
          typeof pNext === "string" &&
          pNext.includes("manager-webpack5") &&
          pNext.includes("preset-react")
        ) {
          pAcc.push([pNext, { runtime: "automatic" }]);
        } else {
          pAcc.push(pNext);
        }
        return pAcc;
      }, []);
    }
    acc.push(next);
    return acc;
  }, []);
});

@ernestostifano
Copy link

Hi @shilman, unfortunately this is still an issue for Storybook Manager (using Storybook v7). If React is not explicitly imported when creating a custom panel, the whole app breaks.

@MihaMixFromGB
Copy link

I'm using Vite and @vitejs/plugin-react helped me.

//vite.config.ts
import react from '@vitejs/plugin-react';

export default defineConfig({
  ...
  plugins: [ react({ jsxRuntime: 'automatic' }) ],
  ...
});

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