pradel / create-react-app-swc

Use swc in your create-react-app for faster compilation, development and tests
MIT License
129 stars 11 forks source link

ReferenceError: React is not defined #9

Closed peteole closed 2 years ago

peteole commented 2 years ago

Hi, after switching to this tool as described in the manual in an existing project, I get the following error: image Anyways starting from a blank project works perfectly with this tool. Any idea what's happening?

MaximeConan commented 2 years ago

You can adapt your craco.config.js to prevent this error. I use the following configuration :

const CracoSwcPlugin = require('craco-swc')

module.exports = {
    plugins: [
        {
            plugin: CracoSwcPlugin,
            options: {
                swcLoaderOptions: {
                    jsc: {
                        transform: {
                            react: {
                                runtime: 'automatic',
                            },
                        },
                    },
                },
            },
        },
    ],
}
NiklasEi commented 2 years ago

The proposed change in craco.config.js above does not solve this error for me.

ianldgs commented 2 years ago

The proposed change in craco.config.js above does solve this error for me on the browser. However, in tests, the plugin apparently doesn't pass the config object forward. My workaround for now:

const CracoSwcPlugin = require("craco-swc");

const jsc = {
  parser: {
    syntax: "typescript",
    tsx: true,
    dynamicImport: true,
  },
  transform: {
    react: {
      runtime: "automatic",
    },
  },
};

CracoSwcPlugin.overrideJestConfig = ({ jestConfig }) => {
  const babelKey = Object.keys(jestConfig.transform)[0];

  jestConfig.transform[babelKey] = [require.resolve("@swc/jest"), { jsc }];

  return jestConfig;
};

module.exports = {
  plugins: [
    {
      plugin: CracoSwcPlugin,
      options: {
        swcLoaderOptions: {
          jsc,
        },
      },
    },
  ],
};
pradel commented 2 years ago

This is now a default in 0.4.0 https://github.com/pradel/create-react-app-swc/releases/tag/craco-swc%400.4.0