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

React 17 new JSX Transform: ReferenceError: React is not defined #28657

Closed
Bartmr opened this issue Dec 16, 2020 · 28 comments · Fixed by #33050
Closed

React 17 new JSX Transform: ReferenceError: React is not defined #28657

Bartmr opened this issue Dec 16, 2020 · 28 comments · Fixed by #33050
Labels
topic: webpack/babel Webpack or babel type: bug An issue or pull request relating to a bug in Gatsby

Comments

@Bartmr
Copy link

Bartmr commented Dec 16, 2020

Description

Gatsby 2.28.1 will throw a ReferenceError: React is not defined if React is not imported on top of the file, but the new JSX Transform (built-in in Gatsby since 2.24) supports files with JSX without a React Import.

Steps to reproduce

I couldn't reproduce this in CodeSandbox but you should easily reproduce this by rendering a component that does not import React.

Expected result

Should not throw the error and allow components without a React import to work normally

Actual result

What happened.
It happens in both development and build mode
The output JS file does not have any React reference:

__webpack_require__.r(__webpack_exports__);
/* WEBPACK VAR INJECTION */(function(__react_refresh_utils__) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ExplorerTemplate", function() { return ExplorerTemplate; });
__webpack_require__.$Refresh$.runtime = __webpack_require__(/*! ./node_modules/react-refresh/runtime.js */ "./node_modules/react-refresh/runtime.js");
__webpack_require__.$Refresh$.setup(module.i);

var _jsxFileName = "/home/bartmr/Documents/unnamed-too/client-side/web-app/src/components/templates/explorer/explorer-template.tsx";
function ExplorerTemplate() {
  return /*#__PURE__*/React.createElement("div", {
    __self: this,
    __source: {
      fileName: _jsxFileName,
      lineNumber: 7,
      columnNumber: 5
    }
  });
}
_c = ExplorerTemplate;

var _c;

__webpack_require__.$Refresh$.register(_c, "ExplorerTemplate");

const currentExports = __react_refresh_utils__.getModuleExports(module.i);
__react_refresh_utils__.registerExportsForReactRefresh(currentExports, module.i);

if (true) {
  const isHotUpdate = !!module.hot.data;
  const prevExports = isHotUpdate ? module.hot.data.prevExports : null;

  if (__react_refresh_utils__.isReactRefreshBoundary(currentExports)) {
    module.hot.dispose(
      /**
       * A callback to performs a full refresh if React has unrecoverable errors,
       * and also caches the to-be-disposed module.
       * @param {*} data A hot module data object from Webpack HMR.
       * @returns {void}
       */
      function hotDisposeCallback(data) {
        // We have to mutate the data object to get data registered and cached
        data.prevExports = currentExports;
      }
    );
    module.hot.accept(
      /**
       * An error handler to allow self-recovering behaviours.
       * @param {Error} error An error occurred during evaluation of a module.
       * @returns {void}
       */
      function hotErrorHandler(error) {
        if (
          false
        ) {}

        if (typeof __react_refresh_test__ !== 'undefined' && __react_refresh_test__) {
          if (window.onHotAcceptError) {
            window.onHotAcceptError(error.message);
          }
        }

        __webpack_require__.c[module.i].hot.accept(hotErrorHandler);
      }
    );

    if (isHotUpdate) {
      if (
        __react_refresh_utils__.isReactRefreshBoundary(prevExports) &&
        __react_refresh_utils__.shouldInvalidateReactRefreshBoundary(prevExports, currentExports)
      ) {
        module.hot.invalidate();
      } else {
        __react_refresh_utils__.enqueueUpdate(
          /**
           * A function to dismiss the error overlay after performing React refresh.
           * @returns {void}
           */
          function updateCallback() {
            if (
              false
            ) {}
          }
        );
      }
    }
  } else {
    if (isHotUpdate && __react_refresh_utils__.isReactRefreshBoundary(prevExports)) {
      module.hot.invalidate();
    }
  }
}
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./node_modules/@pmmmwh/react-refresh-webpack-plugin/lib/runtime/RefreshUtils.js */ "./node_modules/@pmmmwh/react-refresh-webpack-plugin/lib/runtime/RefreshUtils.js")))//# sourceURL=[module]
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiLi9zcmMvY29tcG9uZW50cy90ZW1wbGF0ZXMvZXhwbG9yZXIvZXhwbG9yZXItdGVtcGxhdGUudHN4LmpzIiwic291cmNlcyI6WyIvaG9tZS9iYXJ0bXIvRG9jdW1lbnRzL3VubmFtZWQtdG9vL2NsaWVudC1zaWRlL3dlYi1hcHAvc3JjL2NvbXBvbmVudHMvdGVtcGxhdGVzL2V4cGxvcmVyL2V4cGxvcmVyLXRlbXBsYXRlLnRzeCJdLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgeyBQaGFzZXJQYWdlIH0gZnJvbSAnc3JjL2NvbXBvbmVudHMvcm91dGluZy9waGFzZXItcGFnZS9waGFzZXItcGFnZSc7XG5cblxuXG5leHBvcnQgZnVuY3Rpb24gRXhwbG9yZXJUZW1wbGF0ZSgpIHtcbiAgcmV0dXJuIChcbiAgICA8ZGl2PjwvZGl2PlxuICApO1xufVxuIl0sIm1hcHBpbmdzIjoiOzs7Ozs7QUFJQTtBQUNBO0FBQ0E7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFFQTtBQUpBO0FBQ0E7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7OztBIiwic291cmNlUm9vdCI6IiJ9

Environment

It happens in both development and build mode
It also happens in NodeJS 12

System:
OS: Linux 4.15 Ubuntu 18.04.5 LTS (Bionic Beaver)
CPU: (4) x64 Intel(R) Core(TM) i7-7500U CPU @ 2.70GHz
Shell: 4.4.20 - /bin/bash
Binaries:
Node: 10.16.0 - ~/.nvm/versions/node/v10.16.0/bin/node
npm: 6.9.0 - ~/.nvm/versions/node/v10.16.0/bin/npm
Languages:
Python: 2.7.17 - /usr/bin/python
Browsers:
Chrome: 87.0.4280.88
npmPackages:
gatsby: ^2.28.1 => 2.28.1
gatsby-image: ^2.7.0 => 2.7.0
gatsby-plugin-manifest: ^2.8.0 => 2.8.0
gatsby-plugin-offline: ^3.6.0 => 3.6.0
gatsby-plugin-react-helmet: ^3.6.0 => 3.6.0
gatsby-plugin-robots-txt: ^1.5.3 => 1.5.3
gatsby-plugin-sass: ^2.7.0 => 2.7.0
gatsby-plugin-sharp: ^2.10.1 => 2.10.1
gatsby-plugin-sitemap: ^2.8.0 => 2.8.0
gatsby-plugin-svgr: 2.0.2 => 2.0.2
gatsby-plugin-webpack-bundle-analyser-v2: ^1.1.18 => 1.1.18
gatsby-source-filesystem: ^2.7.0 => 2.7.0
gatsby-transformer-sharp: ^2.8.0 => 2.8.0
npmGlobalPackages:
gatsby-cli: 2.7.49

Possible solution:

I was able to go around this bug by adding this to gatsby-node.js:

exports.onCreateBabelConfig = ({ actions }) => {
  actions.setBabelPlugin({
    name: '@babel/plugin-transform-react-jsx',
    options: {
      runtime: 'automatic',
    },
  });
};
@Bartmr Bartmr added the type: bug An issue or pull request relating to a bug in Gatsby label Dec 16, 2020
@gatsbot gatsbot bot added the status: triage needed Issue or pull request that need to be triaged and assigned to a reviewer label Dec 16, 2020
@nikoladev
Copy link
Contributor

This has been disabled by default because "the ecosystem hasn't adapted yet": #27615

@Bartmr
Copy link
Author

Bartmr commented Dec 16, 2020

@nikoladev At least offer a flag!?

@Bartmr
Copy link
Author

Bartmr commented Dec 16, 2020

@KyleAMathews you can't go around selling that Gatsby has the new JSX Transform and actually having this stated in the React docs and then disable without any warning.

Gatsby is not a personal blog framework. Big companies depend on it

@nikoladev
Copy link
Contributor

@nikoladev At least offer a flag!?

I'm also just a user of Gatsby 🤷‍♀️

You could open up a PR with your proposed flag.

@Bartmr
Copy link
Author

Bartmr commented Dec 16, 2020

@nikoladev ah alright. I already commented all related issues with the solution, but I don't have much time to open a PR and add tests. This is a better job for someone who understands the project. I just left the user side solution

@vladar vladar added topic: webpack/babel Webpack or babel and removed status: triage needed Issue or pull request that need to be triaged and assigned to a reviewer labels Dec 18, 2020
@wardpeet
Copy link
Contributor

@Bartmr have you enabled react-refresh? The biggest architecture issue we're having right now with having a flag for it, plugins like mdx, emotion still need to have the proper /** @jsxImportSource @emotion/react */

@Bartmr
Copy link
Author

Bartmr commented Dec 18, 2020

@wardpeet i do have it enabled, but I do not use any library that needs to mess around with the jsx (like emotion or mdx). Problably should try disabling it. But even if it doesn't work now, it should work in the future since fast refresh is what's planned to be the default.

@github-actions
Copy link

github-actions bot commented Jan 8, 2021

Hiya!

This issue has gone quiet. Spooky quiet. 👻

We get a lot of issues, so we currently close issues after 60 days of inactivity. It’s been at least 20 days since the last update here.
If we missed this issue or if you want to keep it open, please reply here.
As a friendly reminder: the best way to see this issue, or any other, fixed is to open a Pull Request. Check out gatsby.dev/contribute for more information about opening PRs, triaging issues, and contributing!

Thanks for being a part of the Gatsby community! 💪💜

@github-actions github-actions bot added the stale? Issue that may be closed soon due to the original author not responding any more. label Jan 8, 2021
@Dan503
Copy link

Dan503 commented Jan 30, 2021

This is still an issue, please don't close. I ran into this today.

@Dan503
Copy link

Dan503 commented Jan 30, 2021

Thanks @Bartmr for the work around. It worked perfectly! 😊

In gatsby-node.js:

exports.onCreateBabelConfig = ({ actions }) => {
  actions.setBabelPlugin({
    name: '@babel/plugin-transform-react-jsx',
    options: {
      runtime: 'automatic',
    },
  });
};

@github-actions github-actions bot removed the stale? Issue that may be closed soon due to the original author not responding any more. label Jan 30, 2021
@kylegoetz
Copy link
Contributor

kylegoetz commented Feb 4, 2021

I'm getting this error, too, and then when I put in the code from the latest @Dan503 comment, and then run gatsby develop, my new error (which outputs repeatedly for lots of files in my tree):

 ERROR #98124  WEBPACK

Generating development SSR bundle failed

Can't resolve 'react/jsx-runtime' in '/path/to/my-project/src/state'

If you're trying to use a package make sure that 'react/jsx-runtime' is
installed. If you're trying to use a local file make sure that the path is
correct.

File: src/state/ReduxWrapper.js

However, when I execute node from this same directory where I run gatsby develop, I can do this:

> require.resolve('react/jsx-runtime')
'[snip]/node_modules/react/jsx-runtime.js'

So react/jsx-runtime is definitely there.

Edit I've upgraded to Gatsby 2.31.1 and @babel/core and @babel/runtime 7.12.13, plus react and react-dom 17.0.1

Does the fact that I'm writing TypeScript instead of JavaScript have any effect on this? Does Gatsby only apply the babel jsx-runtime plugin to JSX and not TSX files?

@Dan503
Copy link

Dan503 commented Feb 4, 2021

I'm using Typescript in my project and haven't faced that issue.

@kylegoetz It might be that your node_modules folder is corrupt.

Try deleting node_modules and reinstalling. It might fix the issue for you.

@github-actions
Copy link

Hiya!

This issue has gone quiet. Spooky quiet. 👻

We get a lot of issues, so we currently close issues after 60 days of inactivity. It’s been at least 20 days since the last update here.
If we missed this issue or if you want to keep it open, please reply here.
As a friendly reminder: the best way to see this issue, or any other, fixed is to open a Pull Request. Check out gatsby.dev/contribute for more information about opening PRs, triaging issues, and contributing!

Thanks for being a part of the Gatsby community! 💪💜

@github-actions github-actions bot added the stale? Issue that may be closed soon due to the original author not responding any more. label Feb 25, 2021
@steverandy
Copy link

Will this be enabled in Gatsby v3?

@github-actions github-actions bot removed the stale? Issue that may be closed soon due to the original author not responding any more. label Mar 6, 2021
@dvakatsiienko
Copy link

dvakatsiienko commented Mar 19, 2021

It is very strage, but with the all the freshest packages including core ones:

  • Gatsby 3
  • React 17
  • all the latest etc...

Still seeing: React is not defined error even on the simple pages/index.tsx page.

But the expected behavior is the possibility to avoid importing React in each file due to new JSX-transform feature, that was introduced pretty long ago.

I expected that with upgrade to Gatsby 3 it will be packed up inside automatically.
So additional configuration is required?

@mohatt
Copy link

mohatt commented Mar 19, 2021

@steverandy @dvakatsiienko Gatsby 3 supports the new React JSX transform but it is disabled by default (#27615), you need to enable it in your .babelrc config like this:

{
  "presets": [
    [
      "babel-preset-gatsby",
      {
        "reactRuntime": "automatic"
      }
    ]
  ]
}

More info: https://www.gatsbyjs.com/docs/reference/release-notes/v3.0/#react-17

@dvakatsiienko
Copy link

@mohatt Thank you very much!

@github-actions
Copy link

github-actions bot commented Jun 7, 2021

Hiya!

This issue has gone quiet. Spooky quiet. 👻

We get a lot of issues, so we currently close issues after 60 days of inactivity. It’s been at least 20 days since the last update here.
If we missed this issue or if you want to keep it open, please reply here.
As a friendly reminder: the best way to see this issue, or any other, fixed is to open a Pull Request. Check out gatsby.dev/contribute for more information about opening PRs, triaging issues, and contributing!

Thanks for being a part of the Gatsby community! 💪💜

@github-actions github-actions bot added the stale? Issue that may be closed soon due to the original author not responding any more. label Jun 7, 2021
@ibqn
Copy link

ibqn commented Jun 9, 2021

@mohatt your suggestion does not seem to work for me I still end up with this

 ERROR #98123  WEBPACK

Generating development JavaScript bundle failed


/home/ibqn/devel/gatsby3/src/pages/index.js
  1:25  error  'React' must be in scope when using JSX  react/react-in-jsx-scope

✖ 1 problem (1 error, 0 warnings)


failed Building development bundle - 13.352s
ERROR in 
/home/ibqn/devel/gatsby3/src/pages/index.js
  1:25  error  'React' must be in scope when using JSX  react/react-in-jsx-scope

✖ 1 problem (1 error, 0 warnings)


webpack compiled with 1 error

@github-actions github-actions bot removed the stale? Issue that may be closed soon due to the original author not responding any more. label Jun 10, 2021
@codejet
Copy link

codejet commented Jun 12, 2021

Same for me. Adding babel-preset-gatsby and a .babelrc with the required content doesn't get rid of all the error 'React' must be in scope when using JSX react/react-in-jsx-scope. I have all the latest packages installed afaict.

@mohatt
Copy link

mohatt commented Jun 13, 2021

@ibqn @codejet those are just eslint errors due to the rule react/react-in-jsx-scope being set to error. The default eslint config that comes with gatsby doesn't know about the custom babel config in your .babelrc so you will need to use a custom eslint config that disables the following rules:

{
  // ...
  "rules": {
    // ...
    "react/jsx-uses-react": "off",
    "react/react-in-jsx-scope": "off"
  }
}

@codejet btw you don't have to install babel-preset-gatsby package since it comes preinstalled with gatsby

See:
https://www.gatsbyjs.com/docs/how-to/custom-configuration/eslint/
https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html#eslint

@codejet
Copy link

codejet commented Jun 13, 2021

Thanks @mohatt! That seems to work. Only small issue that I still have now is that using shorthand fragments (<>) doesn't work. But could be related to Emotion (facebook/react#20045). In the worst case, importing Fragment solves this for now.

@github-actions
Copy link

github-actions bot commented Jul 3, 2021

Hiya!

This issue has gone quiet. Spooky quiet. 👻

We get a lot of issues, so we currently close issues after 60 days of inactivity. It’s been at least 20 days since the last update here.
If we missed this issue or if you want to keep it open, please reply here.
As a friendly reminder: the best way to see this issue, or any other, fixed is to open a Pull Request. Check out gatsby.dev/contribute for more information about opening PRs, triaging issues, and contributing!

Thanks for being a part of the Gatsby community! 💪💜

@github-actions github-actions bot added the stale? Issue that may be closed soon due to the original author not responding any more. label Jul 3, 2021
@wardpeet
Copy link
Contributor

wardpeet commented Jul 5, 2021

This is great information, we should adjust our internal eslint config based on this setting

@wardpeet wardpeet added not stale and removed stale? Issue that may be closed soon due to the original author not responding any more. labels Jul 5, 2021
@firati-media
Copy link

firati-media commented Jul 25, 2021

Working off @mohatt 's solution, adding this to gatsby-node.js worked for me (I do not have a .babelrc or any other custom babel config in my project). I am on gatsby 3.10.1. I am not encountering any eslint errors.

/* gatsby-node.js */
exports.onCreateBabelConfig = ({ actions }) => {
  actions.setBabelPreset({
    name: 'babel-preset-gatsby',
    options: {
      reactRuntime: 'automatic',
    },
  });
  // ...
}

@iansjk
Copy link

iansjk commented Jul 30, 2021

Thanks @mohatt! That seems to work. Only small issue that I still have now is that using shorthand fragments (<>) doesn't work. But could be related to Emotion (facebook/react#20045). In the worst case, importing Fragment solves this for now.

Just wanted to add that I'm having exactly the same issue--new JSX transform works fine until I try using <>...</> syntax. Would you mind sharing your .babelrc?

@codejet
Copy link

codejet commented Jul 31, 2021

I haven't solved this yet, @iansjk. so, i'm still using <Fragment /> for now.

@christianJessMark
Copy link

christianJessMark commented Aug 27, 2021

I managed to solve the React is undefined SSR error, using the gatsby-node.js solution

exports.onCreateBabelConfig = ({ actions }) => {
  actions.setBabelPreset({
    name: 'babel-preset-gatsby',
    options: {
      reactRuntime: 'automatic',
    },
  })
}

However I can't get Emotion 10 or 11 to work with the css property.

Seeing this in dev tools you have tried to stringify object returned from css function...

Which indicates the the css prop from Emotion is not properly preset in Babel.

I'm using the gatsby-plugin-emotion plugin in gatsby-config.js which used to be fine for everthing, before trying to migrate to the new way to parse JSX.

Setup

    "react": "^17.0.2",
    "gatsby": "3.7.2",
    "typescript": "^4.3.3",
    "gatsby-plugin-emotion": "^6.12.0",
    "@emotion/react": "^11.4.1",
    "@emotion/styled": "^11.3.0",
    "@emotion/babel-plugin": "^11.3.0",
    "@emotion/eslint-plugin": "^11.2.0",

I've tried the .babelrc solution suggested above, but that didn't help me with the React is undefinederror.

EDIT

I finally managed to solve this, by removing gatsby-plugin-emotion from gatsby-config.js and having this in a .babelrc file.

{
  "presets": [
    [
      "@babel/preset-react",
      { "runtime": "automatic", "importSource": "@emotion/react" }
    ]
  ],
  "plugins": ["@emotion"]
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
topic: webpack/babel Webpack or babel type: bug An issue or pull request relating to a bug in Gatsby
Projects
None yet