arackaf / customize-cra

Override webpack configurations for create-react-app 2.0

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

react-scripts 4, JSX transform, useBabelRc and jest

robcaldecott opened this issue Β· comments

react-scripts v4.x now ships with the new React JSX transform which means you no longer need to import React from "react";. πŸ’ƒ

However, if you are using the useBabelRc helper and have supplied your own custom .babelrc (in our case to add react-intl and styled-components plugins) then jest tests will fail anywhere you've removed the React import with:

ReferenceError: React is not defined

It would be great if customize-cra could handle this for us but in the meantime you can workaround this issue by adding the @babel/plugin-transform-react-jsx to your .babelRc, e.g.:

{
  "plugins": [
    [
      "react-intl",
      {
        "extractFromFormatMessageCall": true,
        "idInterpolationPattern": "[sha512:contenthash:base64:6]"
      }
    ],
    "styled-components",
    [
      "@babel/plugin-transform-react-jsx",
      {
        "runtime": "automatic"
      }
    ]
  ]
}

Tests will then run correctly, and your app should still work.

More info here: https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html

Note that I initially tried adding @babel/preset-react to .babelrc:

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

But this did not work and Jest still failed with the same error. I'm not sure why this is the case though. πŸ€·β€β™‚οΈ