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

Update CRACO for create-react-app v5 #353

Closed
tom-ricci opened this issue Dec 14, 2021 · 37 comments
Closed

Update CRACO for create-react-app v5 #353

tom-ricci opened this issue Dec 14, 2021 · 37 comments

Comments

@tom-ricci
Copy link

Create-react-app v5 was just released an hour ago https://github.com/facebook/create-react-app/releases/tag/v5.0.0 and CRACO should probably update to v5 soon.

@OriAmir
Copy link

OriAmir commented Dec 14, 2021

Yeah! I worked with react script 5 next version for a while and craco and things looks OK for me ..
I really wait for the official support of CRACO with CRA5, thanks for your great work !

@ajgassner
Copy link

I just tried it out and it seems the craco-less plugin isn't compatible for now. We will stay at V4 until this issue has been fixed. We need craco-less to compile the less stylesheets of antd.

@supriome
Copy link

#313 #313 (comment)

I also have this problem and hope that it will be fixed soon, and a new version of carco will be released that supports CRA5

@xyy94813
Copy link

I found some dependencies some of react-scrips's dependencies are in node_modules under directory react-scripts.

An implementation like this:
https://github.com/gsoft-inc/craco/blob/8ab5cc92a963f1ed1c3c223ea46aea0cea5d6632/packages/craco/lib/features/webpack/style/postcss.js#L16

it will cause cannot find module problem

@xyy94813
Copy link

About craco-less see DocSpring/craco-less#86 (comment)

@supriome
Copy link

The problem is this line.

https://github.com/gsoft-inc/craco/blob/8ab5cc92a963f1ed1c3c223ea46aea0cea5d6632/packages/craco/lib/features/webpack/style/postcss.js#L54

webpack 5 use postcssOptions as postcss-loader option,while webpack 4 use loader in this way.

webpack 5 use this way
{
  loader: "postcss-loader",
  options: {
    postcssOptions: {
      plugins: [],
    },
  },
},

webpack 4 use this way
{
  loader: "postcss-loader",
  options: {
    plugins: [],
  },
},

In webpack 4, match.loader.options.plugins(); return a function. And In webpack 5 match.loader.options.postcssOptions.plugins; return a object of a function. Click this link to see postcssOptions Description
image

So maybe there another way to get postcssPlugins. Hope this will be fixed soon.

@denchen
Copy link

denchen commented Dec 15, 2021

Anyone else have issues with Jest? I'm getting:

  ● Test suite failed to run

    TypeError: babelJest.createTransformer is not a function

      at createJestBabelTransform (node_modules/@craco/craco/lib/features/jest/create-jest-babel-transform.js:56:22)
      at Object.<anonymous> (node_modules/@craco/craco/lib/features/jest/jest-babel-transform.js:9:8)
      at require.extensions.<computed> (node_modules/ts-node/src/index.ts:1361:43)
      at Object.require.extensions.<computed> [as .js] (node_modules/ts-node/src/index.ts:1361:43)
% npm ls babel-jest
[email protected] /Users/denchen/git/ui
└─┬ [email protected] invalid: "^4.0.0" from node_modules/@craco/craco
  ├── [email protected]
  └─┬ [email protected]
    └─┬ @jest/[email protected]
      └─┬ [email protected]
        └── [email protected] deduped

@andymerskin
Copy link

andymerskin commented Dec 15, 2021

Using craco 6.4.3 next to CRA 5 with only 1 plugin: craco-alias, and things appear to be working swimmingly. Will report back here if anything comes up. 👍

@andymerskin
Copy link

Adding for reference material: @jaxyeh forked and did some nice work on this about a month ago. May be useful if any workarounds are necessary:
jaxyeh/craco@9f3faa7

@Nefcanto
Copy link

I'm using Tailwind 3 and here's my craco.config.js:

module.exports = {
  style: {
    postcss: {
      plugins: [
        require('tailwindcss'),
        require('autoprefixer'),
      ],
    },
  },
  webpack: {
    alias: resolvedAliases,
    // this config, causes HolismIcon to throw react error 321 for builds
    configure: {
      resolve: {
        symlinks: false,
      },
    },
  },
}

I upgraded my react-scripts from V4 to V5 and it gives me this error:

TypeError: match.loader.options.plugins is not a function

@Nefcanto
Copy link

Here's what I get now when I try to install craco on create-react-app:

npm install @craco/craco --save
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR! 
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/react-scripts
npm ERR!   react-scripts@"5.0.0" from the root project
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! peer react-scripts@"^4.0.0" from @craco/[email protected]
npm ERR! node_modules/@craco/craco
npm ERR!   @craco/craco@"*" from the root project
npm ERR! 
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR! 
npm ERR! See /root/.npm/eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2021-12-18T13_07_05_364Z-debug-0.log

@OriAmir
Copy link

OriAmir commented Dec 18, 2021

Here's what I get now when I try to install craco on create-react-app:

npm install @craco/craco --save
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR! 
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/react-scripts
npm ERR!   react-scripts@"5.0.0" from the root project
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! peer react-scripts@"^4.0.0" from @craco/[email protected]
npm ERR! node_modules/@craco/craco
npm ERR!   @craco/craco@"*" from the root project
npm ERR! 
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR! 
npm ERR! See /root/.npm/eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2021-12-18T13_07_05_364Z-debug-0.log

it's because craco peer dep isreact-scriptsversion 4 , when they will update that it's will be fine.
You can resolve that for now with that flag : --legacy-peer-deps -> npm install craco --legacy-peer-deps , it's happening in NPM>6 that it's try to install also the peer deps , read more here: https://stackoverflow.com/questions/66239691/what-does-npm-install-legacy-peer-deps-do-exactly-when-is-it-recommended-wh

@kiril-daskalov
Copy link

I'm using Tailwind 3 and here's my craco.config.js:

module.exports = {
  style: {
    postcss: {
      plugins: [
        require('tailwindcss'),
        require('autoprefixer'),
      ],
    },
  },
  webpack: {
    alias: resolvedAliases,
    // this config, causes HolismIcon to throw react error 321 for builds
    configure: {
      resolve: {
        symlinks: false,
      },
    },
  },
}

I upgraded my react-scripts from V4 to V5 and it gives me this error:

TypeError: match.loader.options.plugins is not a function

Tailwind 3 configuration in CRACO is not needed anymore.

https://tailwindcss.com/docs/guides/create-react-app

@Nefcanto
Copy link

@kiril-daskalov yeah Tailwind 3 does not need CRACO anymore. But I still need CRACO because of Webpack aliases and symbolic links.

@Nefcanto
Copy link

I upgraded to Tailwind 3. Now my app works in the development environment. However, my app breaks in build.

Here's my craco.config.js file:

const path = require(`path`);
const aliases = {
    '@Form': 'src/Components/Form/Form',
    '@FormTwo': 'src/Components/Form/FormTwo',
    '@List': 'src/Components/List/List',
    '@Browse': 'src/Components/Browse/Browse',
    '@Dashboard': 'src/Components/Dashboard/Dashboard',
    '@Panel': 'src/Panel/Panel',
};

const resolvedAliases = Object.fromEntries(
    Object.entries(aliases).map(([key, value]) => [key, path.resolve(__dirname, value)]),
);

module.exports = {
    webpack: {
        alias: resolvedAliases
    }
}

It fails with this message:

Step 13/20 : RUN npm run build
 ---> Running in 7629d400606c

> [email protected] build
> craco build

Creating an optimized production build...
Failed to compile.

Module not found: Error: Can't resolve '...' in '/Company/Project/src'


The command '/bin/sh -c npm run build' returned a non-zero code: 1

@jamshally
Copy link

Anyone else have issues with Jest? I'm getting:

  ● Test suite failed to run

    TypeError: babelJest.createTransformer is not a function

      at createJestBabelTransform (node_modules/@craco/craco/lib/features/jest/create-jest-babel-transform.js:56:22)
      at Object.<anonymous> (node_modules/@craco/craco/lib/features/jest/jest-babel-transform.js:9:8)
      at require.extensions.<computed> (node_modules/ts-node/src/index.ts:1361:43)
      at Object.require.extensions.<computed> [as .js] (node_modules/ts-node/src/index.ts:1361:43)
% npm ls babel-jest
[email protected] /Users/denchen/git/ui
└─┬ [email protected] invalid: "^4.0.0" from node_modules/@craco/craco
  ├── [email protected]
  └─┬ [email protected]
    └─┬ @jest/[email protected]
      └─┬ [email protected]
        └── [email protected] deduped

I am getting the exact issue as @denchen. I haven't found a solution yet. Adding here for visibility.

@cgooderham94
Copy link

Anyone else have issues with Jest? I'm getting:

  ● Test suite failed to run

    TypeError: babelJest.createTransformer is not a function

      at createJestBabelTransform (node_modules/@craco/craco/lib/features/jest/create-jest-babel-transform.js:56:22)
      at Object.<anonymous> (node_modules/@craco/craco/lib/features/jest/jest-babel-transform.js:9:8)
      at require.extensions.<computed> (node_modules/ts-node/src/index.ts:1361:43)
      at Object.require.extensions.<computed> [as .js] (node_modules/ts-node/src/index.ts:1361:43)
% npm ls babel-jest
[email protected] /Users/denchen/git/ui
└─┬ [email protected] invalid: "^4.0.0" from node_modules/@craco/craco
  ├── [email protected]
  └─┬ [email protected]
    └─┬ @jest/[email protected]
      └─┬ [email protected]
        └── [email protected] deduped

I am getting the exact issue as @denchen. I haven't found a solution yet. Adding here for visibility.

Ditto - I too face the same issue as @denchen and @jamshally - It seems this is becoming a common issue. Is it possible there is a workaround or if a fix may be implemented soon?

[email protected] /Users/charlesgooderham/htdocs/charliegooderham.dev
├─┬ [email protected]
│ └─┬ @jest/[email protected]
│   └─┬ [email protected]
│     └── [email protected] deduped
├─┬ [email protected]
│ └── [email protected]
└─┬ [email protected]
  └── [email protected]

@mpsijm
Copy link

mpsijm commented Dec 23, 2021

I updated react-scripts to 5.0.0 today (with npm i --legacy-peer-deps), and it runs mostly fine for me. I use Tailwind v3 as well. I only have the following minor issues:

  • Webpack v5 no longer polyfills Node's core modules, so as a workaround, I added the node-polyfill-webpack-plugin to my craco.config.js: https://stackoverflow.com/a/65556946. I'm not sure if this is caused by one of my dependencies or by CRACO.
  • I get deprecation warnings when running craco start, right before it clears the console:
    image

@ihoey
Copy link

ihoey commented Dec 24, 2021

I just tried it out and it seems the craco-less plugin isn't compatible for now. We will stay at V4 until this issue has been fixed. We need craco-less to compile the less stylesheets of antd.

craco-less already fixed

@popuguytheparrot
Copy link

popuguytheparrot commented Dec 24, 2021

TypeError: babelJest.createTransformer is not a function
at createJestBabelTransform (/node_modules/@craco/craco/lib/features/jest/create-jest-babel-transform.js:56:22)

@AmirAsghary
Copy link

Is there an ETA for the CRACO's support for webpackV5?

@Nefcanto
Copy link

Any news regarding this upgrade? We are faced with the eject decision and we don't really want to do it. CRACO is a neat solution.

@patricklafrance
Copy link
Contributor

Info available here #313

@cabello
Copy link

cabello commented Dec 27, 2021

In my case as soon as I upgraded react-scripts:

Module not found: Error: You attempted to import /Users/cabello/project/node_modules/react-refresh/runtime.js which falls outside of the project src/ directory. Relative imports outside of src/ are not supported.
You can either move it inside src/, or add a symlink to it from project's node_modules/.

I also got different errors depending on what I attempted to update.

And this is my craco config:

const CopyWebpackPlugin = require('copy-webpack-plugin');
const RollbarSourceMapPlugin = require('rollbar-sourcemap-webpack-plugin');

const rollbarPlugin = {
  overrideWebpackConfig: ({ webpackConfig }) => {
    if (process.env.GENERATE_SOURCEMAP === 'true') {
      webpackConfig.plugins.push(
        new RollbarSourceMapPlugin({
          accessToken: process.env.ROLLBAR_ACCESS_TOKEN,
          publicPath: 'https://example.com',
          version: process.env.REACT_APP_COMMIT_REF,
        })
      );
    }
    return webpackConfig;
  },
};

module.exports = {
  plugins: [{ plugin: rollbarPlugin }],
  babel: {
    loaderOptions: (babelLoaderOptions) => {
      const origBabelPresetCRAIndex = babelLoaderOptions.presets.findIndex(
        (preset) => {
          return preset[0].includes('babel-preset-react-app');
        }
      );

      const origBabelPresetCRA =
        babelLoaderOptions.presets[origBabelPresetCRAIndex];

      babelLoaderOptions.presets[
        origBabelPresetCRAIndex
      ] = function overridenPresetCRA(api, opts, env) {
        const babelPresetCRAResult = require(origBabelPresetCRA[0])(
          api,
          origBabelPresetCRA[1],
          env
        );

        babelPresetCRAResult.presets.forEach((preset) => {
          // detect @babel/preset-react with {development: true, runtime: 'automatic'}
          const isReactPreset =
            preset &&
            preset[1] &&
            preset[1].runtime === 'automatic' &&
            preset[1].development === true;
          if (isReactPreset) {
            preset[1].importSource = '@welldone-software/why-did-you-render';
          }
        });

        return babelPresetCRAResult;
      };

      return babelLoaderOptions;
    },
    plugins: [
      [
        'react-intl',
        {
          idInterpolationPattern: '[sha512:contenthash:base64:6]',
          extractFromFormatMessageCall: true,
          ast: true,
        },
      ],
    ],
  },
  webpack: {
    plugins: {
      alias: {
        'react-redux':
          process.env.NODE_ENV === 'development'
            ? 'react-redux/lib'
            : 'react-redux',
      },
      add: [
        new CopyWebpackPlugin({
          patterns: [
            {
              from: 'node_modules/some-library',
              to: 'some-library',
            },
          ],
        }),
      ],
    },
  },
};

NiGhTTraX added a commit to NiGhTTraX/ts-monorepo that referenced this issue Dec 28, 2021
`craco` doesn't yet support v5, and it's causing npm to freak out. See
dilanx/craco#353.
NiGhTTraX added a commit to NiGhTTraX/ts-monorepo that referenced this issue Dec 28, 2021
`craco` doesn't yet support v5, and it's causing npm to freak out. See
dilanx/craco#353.
@edvincandon
Copy link

edvincandon commented Dec 31, 2021

Anyone else have issues with Jest? I'm getting:

  ● Test suite failed to run

    TypeError: babelJest.createTransformer is not a function

      at createJestBabelTransform (node_modules/@craco/craco/lib/features/jest/create-jest-babel-transform.js:56:22)
      at Object.<anonymous> (node_modules/@craco/craco/lib/features/jest/jest-babel-transform.js:9:8)
      at require.extensions.<computed> (node_modules/ts-node/src/index.ts:1361:43)
      at Object.require.extensions.<computed> [as .js] (node_modules/ts-node/src/index.ts:1361:43)
% npm ls babel-jest
[email protected] /Users/denchen/git/ui
└─┬ [email protected] invalid: "^4.0.0" from node_modules/@craco/craco
  ├── [email protected]
  └─┬ [email protected]
    └─┬ @jest/[email protected]
      └─┬ [email protected]
        └── [email protected] deduped

I am getting the exact issue as @denchen. I haven't found a solution yet. Adding here for visibility.

@denchen @jamshally @cgooderham94 - Same problem here, got it to work by fiddling around in my node_modules, maybe my resolution can help. I'd open a PR, but I'm not well-versed enough on the craco codebase yet to have a proper solution covering all cases.

Environment

node v15.14.0
craco v6.4.3
react-scripts v5.0.0
jest v27.4.5

craco.config.js (jest)

module.exports = {
  /* ... */
  jest: {
        configure: (jestConfig, { env, paths, resolve, rootDir }) => {
            jestConfig.setupFilesAfterEnv.push(`${rootDir}/../../jest.setup.js`);

            /* avoid ES modules */
            jestConfig.moduleNameMapper['^lodash-es$'] = 'lodash';
            jestConfig.moduleNameMapper['^@antv/xflow-core/es/(.*)'] = '@antv/xflow-core/lib/$1';

            return jestConfig;
        }
    }
}

Resolution steps

https://github.com/gsoft-inc/craco/blob/8ab5cc92a963f1ed1c3c223ea46aea0cea5d6632/packages/craco/lib/features/jest/create-jest-babel-transform.js#L56

You actually just need to call it from the default export (jestjs/jest#11444)

return babelJest.default.createTransformer(craBabelTransformer);

https://github.com/gsoft-inc/craco/blob/8ab5cc92a963f1ed1c3c223ea46aea0cea5d6632/packages/craco/lib/features/jest/jest-babel-transform.js#L12

For some reason (haven't really checked the full codebase : don't know what dependency update caused this) - the correct path to access the jest globals object would be

jestBabelTransform = createJestBabelTransform(config.config.globals._cracoConfig);

Hope it can help while we wait for a fix (or this to turn into a PR ?)..

@flyingcrp
Copy link

I just tried it out and it seems the craco-less plugin isn't compatible for now. We will stay at V4 until this issue has been fixed. We need craco-less to compile the less stylesheets of antd.

time to move on,😄 feat: support for CRA v5

@andycanderson
Copy link

I just tried it out and it seems the craco-less plugin isn't compatible for now. We will stay at V4 until this issue has been fixed. We need craco-less to compile the less stylesheets of antd.

time to move on,😄 feat: support for CRA v5

What version craco-less are you using? At a glance "craco-less": "^2.0.0", seems to be working

@thehogfather
Copy link

Anyone else have issues with Jest? I'm getting:

  ● Test suite failed to run

    TypeError: babelJest.createTransformer is not a function

      at createJestBabelTransform (node_modules/@craco/craco/lib/features/jest/create-jest-babel-transform.js:56:22)
      at Object.<anonymous> (node_modules/@craco/craco/lib/features/jest/jest-babel-transform.js:9:8)
      at require.extensions.<computed> (node_modules/ts-node/src/index.ts:1361:43)
      at Object.require.extensions.<computed> [as .js] (node_modules/ts-node/src/index.ts:1361:43)
% npm ls babel-jest
[email protected] /Users/denchen/git/ui
└─┬ [email protected] invalid: "^4.0.0" from node_modules/@craco/craco
  ├── [email protected]
  └─┬ [email protected]
    └─┬ @jest/[email protected]
      └─┬ [email protected]
        └── [email protected] deduped

I am getting the exact issue as @denchen. I haven't found a solution yet. Adding here for visibility.

Ditto - I too face the same issue as @denchen and @jamshally - It seems this is becoming a common issue. Is it possible there is a workaround or if a fix may be implemented soon?

[email protected] /Users/charlesgooderham/htdocs/charliegooderham.dev
├─┬ [email protected]
│ └─┬ @jest/[email protected]
│   └─┬ [email protected]
│     └── [email protected] deduped
├─┬ [email protected]
│ └── [email protected]
└─┬ [email protected]
  └── [email protected]

One possible work around for the babel-jest issue (until a new version of craco that supports react-scripts 5 is released) is to update your package.json to use the underlying react-scripts instead of craco for tests. You would also need to move any jest specific configs from craco to the package.json file. Might not work if you have very complex webpack setup for tests. So for example:
Before in package.json "scripts" section:

    "test": "craco test --env=jsdom",

After

    "test": "react-scripts test --env=jsdom",

@kitayoshi
Copy link

@supriome I used patch-package to patch this file of @craco/[email protected] like:

diff --git a/node_modules/@craco/craco/lib/features/webpack/style/postcss.js b/node_modules/@craco/craco/lib/features/webpack/style/postcss.js
index c66146a..31372ef 100644
--- a/node_modules/@craco/craco/lib/features/webpack/style/postcss.js
+++ b/node_modules/@craco/craco/lib/features/webpack/style/postcss.js
@@ -50,8 +50,12 @@ function extendsPostcss(match, { plugins, env }) {
         } else {
             let craPlugins = [];
 
-            if (match.loader.options) {
-                craPlugins = match.loader.options.plugins();
+            if (match.loader.options.postcssOptions) {
+                if (typeof match.loader.options.postcssOptions === "function") {
+                    craPlugins = match.loader.options.postcssOptions().plugins;
+                } else {
+                    craPlugins = match.loader.options.postcssOptions.plugins;
+                }
             }
 
             postcssPlugins = craPlugins || [];
@@ -63,13 +67,20 @@ function extendsPostcss(match, { plugins, env }) {
             log("Added PostCSS plugins.");
         }
 
-        if (match.loader.options) {
-            match.loader.options.plugins = () => postcssPlugins;
-        } else {
-            match.loader.options = {
-                plugins: () => postcssPlugins
-            };
+        let postcssOptions
+
+        if (match.loader.options.postcssOptions) {
+            if (typeof match.loader.options.postcssOptions === "function") {
+                postcssOptions = match.loader.options.postcssOptions();
+            } else {
+                postcssOptions = match.loader.options.postcssOptions
+            }
         }
+
+        match.loader.options.postcssOptions = () => ({
+            ...postcssOptions,
+            plugins: postcssPlugins
+        });
     }
 }
 

This issue body was partially generated by patch-package.

@kitsunekyo
Copy link

craco is still needed with tailwind 3 for anyone using postcss-import or other extensions.
https://tailwindcss.com/docs/using-with-preprocessors#build-time-imports

@agusterodin
Copy link

craco is still needed with tailwind 3 for anyone using postcss-import or other extensions. https://tailwindcss.com/docs/using-with-preprocessors#build-time-imports

Or something as simple as using a tailwind config file from any path other than the project root (tailwind config file housed in a common UI library, for example)

@patricklafrance
Copy link
Contributor

Duplicate of #378

@patricklafrance patricklafrance marked this as a duplicate of #378 Jan 13, 2022
@tom-ricci
Copy link
Author

Isn't 378 technically a duplicate of this? :p

/j

@patricklafrance
Copy link
Contributor

@tom-ricci hehe yeah technically you're right ;)

@xyy94813
Copy link

Anyone else have issues with Jest? I'm getting:

  ● Test suite failed to run

    TypeError: babelJest.createTransformer is not a function

      at createJestBabelTransform (node_modules/@craco/craco/lib/features/jest/create-jest-babel-transform.js:56:22)
      at Object.<anonymous> (node_modules/@craco/craco/lib/features/jest/jest-babel-transform.js:9:8)
      at require.extensions.<computed> (node_modules/ts-node/src/index.ts:1361:43)
      at Object.require.extensions.<computed> [as .js] (node_modules/ts-node/src/index.ts:1361:43)
% npm ls babel-jest
[email protected] /Users/denchen/git/ui
└─┬ [email protected] invalid: "^4.0.0" from node_modules/@craco/craco
  ├── [email protected]
  └─┬ [email protected]
    └─┬ @jest/[email protected]
      └─┬ [email protected]
        └── [email protected] deduped

I am getting the exact issue as @denchen. I haven't found a solution yet. Adding here for visibility.

Ditto - I too face the same issue as @denchen and @jamshally - It seems this is becoming a common issue. Is it possible there is a workaround or if a fix may be implemented soon?

[email protected] /Users/charlesgooderham/htdocs/charliegooderham.dev
├─┬ [email protected]
│ └─┬ @jest/[email protected]
│   └─┬ [email protected]
│     └── [email protected] deduped
├─┬ [email protected]
│ └── [email protected]
└─┬ [email protected]
  └── [email protected]

One possible work around for the babel-jest issue (until a new version of craco that supports react-scripts 5 is released) is to update your package.json to use the underlying react-scripts instead of craco for tests. You would also need to move any jest specific configs from craco to the package.json file. Might not work if you have very complex webpack setup for tests. So for example: Before in package.json "scripts" section:

    "test": "craco test --env=jsdom",

After

    "test": "react-scripts test --env=jsdom",

My workaround in current version of CRACO:

// craco.config.js
jest: {
    configure: jestConfig => lodash.merge(jestConfig, {
      transform: {
        // https://github.com/gsoft-inc/craco/issues/353#issuecomment-1003301013
        '^.+\\.(js|jsx|mjs|cjs|ts|tsx)$': './libs/jest-babel-transform.js',
      },
    }),
  },
// jest-babel-transform.js

/* eslint-disable no-underscore-dangle */
/* eslint-disable max-len */
// eslint-disable-next-line import/no-extraneous-dependencies
const babelJest = require('babel-jest');

const { isArray } = Array;

/**
 * To check if support jsx-runtime
 * Copy from https://github.com/facebook/create-react-app/blob/2b1161b34641bb4d2f269661cd636bbcd4888406/packages/react-scripts/config/jest/babelTransform.js#L12
 */
const hasJsxRuntime = (() => {
  if (process.env.DISABLE_NEW_JSX_TRANSFORM === 'true') {
    return false;
  }

  try {
    require.resolve('react/jsx-runtime');
    return true;
  } catch (e) {
    return false;
  }
})();

function createJestBabelTransform(cracoConfig) {
  const craBabelTransformer = {
    presets: [
      [
        'babel-preset-react-app',
        {
          runtime: hasJsxRuntime ? 'automatic' : 'classic',
        },
      ],
    ],
    babelrc: false,
    configFile: false,
  };

  if (cracoConfig) {
    const { addPresets, addPlugins } = cracoConfig.jest.babel;

    if (cracoConfig.babel) {
      if (addPresets) {
        const { presets } = cracoConfig.babel;

        if (isArray(presets)) {
          craBabelTransformer.presets = craBabelTransformer.presets.concat(presets);
        }
      }

      if (addPlugins) {
        const { plugins } = cracoConfig.babel;

        if (isArray(plugins)) {
          craBabelTransformer.plugins = plugins;
        }
      }
    }
  }
  return babelJest.default.createTransformer(craBabelTransformer);
}

let jestBabelTransform;

// cracoConfig is only available inside the transform, but the transform needs to include whatever options cracoConfig
// specifies. So, the first time this transform is run, it generates a new transform -- using cracoConfig -- and
// uses that to process files.
module.exports = {
  ...createJestBabelTransform(),
  process(src, filename, config, transformOptions) {
    if (!jestBabelTransform) {
      jestBabelTransform = createJestBabelTransform(config.config.globals._cracoConfig);
    }

    return jestBabelTransform.process(src, filename, config, transformOptions);
  },
};

@tom-ricci
Copy link
Author

@xyy94813 move to #378

@conatus
Copy link

conatus commented Feb 16, 2022

Anyone else have issues with Jest? I'm getting:

  ● Test suite failed to run

    TypeError: babelJest.createTransformer is not a function

      at createJestBabelTransform (node_modules/@craco/craco/lib/features/jest/create-jest-babel-transform.js:56:22)
      at Object.<anonymous> (node_modules/@craco/craco/lib/features/jest/jest-babel-transform.js:9:8)
      at require.extensions.<computed> (node_modules/ts-node/src/index.ts:1361:43)
      at Object.require.extensions.<computed> [as .js] (node_modules/ts-node/src/index.ts:1361:43)
% npm ls babel-jest
[email protected] /Users/denchen/git/ui
└─┬ [email protected] invalid: "^4.0.0" from node_modules/@craco/craco
  ├── [email protected]
  └─┬ [email protected]
    └─┬ @jest/[email protected]
      └─┬ [email protected]
        └── [email protected] deduped

I am getting the exact issue as @denchen. I haven't found a solution yet. Adding here for visibility.

@denchen @jamshally @cgooderham94 - Same problem here, got it to work by fiddling around in my node_modules, maybe my resolution can help. I'd open a PR, but I'm not well-versed enough on the craco codebase yet to have a proper solution covering all cases.

Environment

node v15.14.0
craco v6.4.3
react-scripts v5.0.0
jest v27.4.5

craco.config.js (jest)

module.exports = {
  /* ... */
  jest: {
        configure: (jestConfig, { env, paths, resolve, rootDir }) => {
            jestConfig.setupFilesAfterEnv.push(`${rootDir}/../../jest.setup.js`);

            /* avoid ES modules */
            jestConfig.moduleNameMapper['^lodash-es$'] = 'lodash';
            jestConfig.moduleNameMapper['^@antv/xflow-core/es/(.*)'] = '@antv/xflow-core/lib/$1';

            return jestConfig;
        }
    }
}

Resolution steps

https://github.com/gsoft-inc/craco/blob/8ab5cc92a963f1ed1c3c223ea46aea0cea5d6632/packages/craco/lib/features/jest/create-jest-babel-transform.js#L56

You actually just need to call it from the default export (facebook/jest#11444)

return babelJest.default.createTransformer(craBabelTransformer);

https://github.com/gsoft-inc/craco/blob/8ab5cc92a963f1ed1c3c223ea46aea0cea5d6632/packages/craco/lib/features/jest/jest-babel-transform.js#L12

For some reason (haven't really checked the full codebase : don't know what dependency update caused this) - the correct path to access the jest globals object would be

jestBabelTransform = createJestBabelTransform(config.config.globals._cracoConfig);

Hope it can help while we wait for a fix (or this to turn into a PR ?)..

Thanks for making CRACO!

Having the same issue here.

The workaround provided by @xyy94813 works well.

Meanwhile, Jest have released an alpha which makes this problem go away seemingly - https://github.com/facebook/jest/releases/tag/v28.0.0-alpha.1 - see jestjs/jest#11444 for further discussion.

It seems that Jest being upgraded to this version in the underlying packages will make this go away. Seems that discussion has moved onto #378, but recording here as this issue doesn't come up over there.

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

No branches or pull requests