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 to CRA 5 **** #378

Closed
patricklafrance opened this issue Jan 13, 2022 · 58 comments
Closed

**** Update to CRA 5 **** #378

patricklafrance opened this issue Jan 13, 2022 · 58 comments

Comments

@patricklafrance
Copy link
Contributor

patricklafrance commented Jan 13, 2022

Finally, some news about an update to CRACO for CRA 5 :)

We are aware that most of you are eager to migrate to CRA 5 and right now we are what prevents you from doing so. Thank you for your patience.

Sadly, it seem like every major update of CRA happens right before the christmas holiday. Most of us at GSoft only came back to work this week.

The good news is that we assembled a team who will be working on this in the coming weeks. I can't give you any ETA, i'll let the team give you updates about a release date but our goal is to get this out ASAP.

Meanwhile, please use this thread to make us know about any NEW issues you find after upgrading to CRA 5. It will help the team aknowledge what have to be done to support CRA 5. Before commenting, please make sure it's not already mentionned in any of those issues: #377 #353 #313

Don't open a new issue about CRA 5, it doesn't help.

Don't comment to ask for an update or let us know that you are waiting for this, it doesn't help. You can show your support with an emoji on this message instead.

Thank you!

Patrick

@picosam
Copy link

picosam commented Jan 14, 2022

Thank you, and happy holidays! I'm having this warning when running craco start:

(node:26217) [DEP_WEBPACK_DEV_SERVER_HTTPS] DeprecationWarning: 'https' option is deprecated. Please use the 'server' option.
(Use `node --trace-deprecation ...` to show where the warning was created)
(node:26217) [DEP_WEBPACK_DEV_SERVER_ON_AFTER_SETUP_MIDDLEWARE] DeprecationWarning: 'onAfterSetupMiddleware' option is deprecated. Please use the 'setupMiddlewares' option.
(node:26217) [DEP_WEBPACK_DEV_SERVER_ON_BEFORE_SETUP_MIDDLEWARE] DeprecationWarning: 'onBeforeSetupMiddleware' option is deprecated. Please use the 'setupMiddlewares' option.

Here's my craco.config.js file:

const path = require('path');
const { getLoader, loaderByName } = require('@craco/craco');

const uiPath = path.join(__dirname, '../../packages/ui');

module.exports = {
	webpack: {
		configure: (webpackConfig, { env, paths }) => {
			const { isFound, match } = getLoader(webpackConfig, loaderByName('babel-loader'));
			if (isFound) {
				const include = Array.isArray(match.loader.include) ? match.loader.include : [match.loader.include];
				match.loader.include = include.concat([
					uiPath,
				]);
			}
			return webpackConfig;
		},
	},
};

As you can see, I'm using Craco for a monorepo setup, where I have 2 CRA apps referencing the same UI package.

@popuguytheparrot
Copy link

maybe milestone or something else for progress?

@olso
Copy link

olso commented Jan 18, 2022

Update: for now I used patch-package and added .babelrc with that one plugin I needed

diff --git a/node_modules/@craco/craco/lib/features/jest/create-jest-babel-transform.js b/node_modules/@craco/craco/lib/features/jest/create-jest-babel-transform.js
index 5c5a347..0d5c911 100644
--- a/node_modules/@craco/craco/lib/features/jest/create-jest-babel-transform.js
+++ b/node_modules/@craco/craco/lib/features/jest/create-jest-babel-transform.js
@@ -28,7 +28,7 @@ function createJestBabelTransform(cracoConfig) {
                 }
             ]
         ],
-        babelrc: false,
+        babelrc: true, // patch
         configFile: false
     };

Hey, I'm trying out the latest commit 7aab18d

gitpkg.now.sh is just helper for installing lerna like packages from git

yarn add -D 'https://gitpkg.now.sh/gsoft-inc/craco/packages/craco?7aab18d485074588a4f63455ec2627340bd6240c'

and it seems like babel plugins are not forwarded to craco test (it works for craco start)

const CracoAlias = require("craco-alias");

module.exports = {
  plugins: [
    {
      plugin: CracoAlias,
      options: {
        source: "tsconfig",
        /* tsConfigPath should point to the file where "paths" are specified */
        tsConfigPath: "./tsconfig.paths.json",
      },
    },
  ],
  babel: {
    plugins: ["relay"],
  },
  webpack: {
    alias: {
      "@mui/styled-engine": "@mui/styled-engine-sc",
    },
  },
};

Maybe this call stack helps

 FAIL  src/App.test.tsx
  ✕ renders explore (101 ms)

  ● renders explore

    Invariant Violation: graphql: Unexpected invocation at runtime. Either the Babel transform was not set up, or it failed to identify this call site. Make sure it is being used verbatim as `graphql`. Note also that there cannot be a space between graphql and the backtick that follows.

      69 |   }, []);
      70 |
    > 71 |   const [commitMakeBasket] = useMutation<BasketMakeMutation>(graphql`
         |                                                                      ^
      72 |     mutation BasketMakeMutation($input: BasketInput!) {
      73 |       basket: makeBasket(input: $input) {
      74 |         id

      at invariant (node_modules/invariant/invariant.js:40:15)
      at graphql (node_modules/relay-runtime/lib/query/GraphQLTag.js:25:52)
      at BasketProvider (src/contexts/Basket/index.tsx:71:70)
      at renderWithHooks (node_modules/react-dom/cjs/react-dom.development.js:14985:18)
      at mountIndeterminateComponent (node_modules/react-dom/cjs/react-dom.development.js:17811:13)
      at beginWork (node_modules/react-dom/cjs/react-dom.development.js:19049:16)
      at HTMLUnknownElement.callCallback (node_modules/react-dom/cjs/react-dom.development.js:3945:14)
      at HTMLUnknownElement.callTheUserObjectsOperation (node_modules/jsdom/lib/jsdom/living/generated/EventListener.js:26:30)
      at innerInvokeEventListeners (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:338:25)
      at invokeEventListeners (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:274:3)
      at HTMLUnknownElementImpl._dispatch (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:221:9)
      at HTMLUnknownElementImpl.dispatchEvent (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:94:17)
      at HTMLUnknownElement.dispatchEvent (node_modules/jsdom/lib/jsdom/living/generated/EventTarget.js:231:34)
      at Object.invokeGuardedCallbackDev (node_modules/react-dom/cjs/react-dom.development.js:3994:16)
      at invokeGuardedCallback (node_modules/react-dom/cjs/react-dom.development.js:4056:31)
      at beginWork$1 (node_modules/react-dom/cjs/react-dom.development.js:23964:7)
      at performUnitOfWork (node_modules/react-dom/cjs/react-dom.development.js:22779:12)
      at workLoopSync (node_modules/react-dom/cjs/react-dom.development.js:22707:5)
      at renderRootSync (node_modules/react-dom/cjs/react-dom.development.js:22670:7)
      at performSyncWorkOnRoot (node_modules/react-dom/cjs/react-dom.development.js:22293:18)
      at scheduleUpdateOnFiber (node_modules/react-dom/cjs/react-dom.development.js:21881:7)
      at updateContainer (node_modules/react-dom/cjs/react-dom.development.js:25482:3)
      at node_modules/react-dom/cjs/react-dom.development.js:26021:7
      at unbatchedUpdates (node_modules/react-dom/cjs/react-dom.development.js:22431:12)
      at legacyRenderSubtreeIntoContainer (node_modules/react-dom/cjs/react-dom.development.js:26020:5)
      at Object.render (node_modules/react-dom/cjs/react-dom.development.js:26103:10)
      at node_modules/@testing-library/react/dist/pure.js:101:25
      at batchedUpdates$1 (node_modules/react-dom/cjs/react-dom.development.js:22380:12)
      at act (node_modules/react-dom/cjs/react-dom-test-utils.development.js:1042:14)
      at render (node_modules/@testing-library/react/dist/pure.js:97:26)
      at Object.<anonymous> (src/App.test.tsx:15:3)

Possibly related: #294 #183

NiGhTTraX added a commit to NiGhTTraX/ts-monorepo that referenced this issue Jan 24, 2022
This reverts the workarounds for #159, #74 and #60, as they are no
longer needed.

There are a few peer dependency warnings, though the examples work just
fine:

- The one for NextJS is tracked in
vercel/next.js#31887.
- CRACO support for CRA@5 is tracked in
dilanx/craco#378.
- The warnings for CRA are tracked in
facebook/create-react-app#11982, except for
the `ts-jest` one which is expected, since we're using CRA's `jest`.
@mousse-tache
Copy link

mousse-tache commented Jan 25, 2022

Hey guys,

I'm Felix, one of Patrick's colleagues at GSoft and I've been working on CRA 5 support.

I've just published an alpha version if you want to test it out, some of the issues that have been frequently mentioned are addressed in the alpha. See here and here

  • Update peer and dev dependencies to CRA 5.
  • Fix postcss options.
  • Creation of CRA 4 recipes folder.
  • Jest support for CRA 5.

Cheers

@olivierbeaulieu
Copy link

I have updated to 7.0.0-alpha.0 and everything seems to work fine! (Although I did have to mess around a bunch of react-scripts related errors all morning...)

Thanks a lot!

@jereklas
Copy link

jereklas commented Jan 28, 2022

Hey, I'm trying out the latest commit 7aab18d

gitpkg.now.sh is just helper for installing lerna like packages from git

yarn add -D 'https://gitpkg.now.sh/gsoft-inc/craco/packages/craco?7aab18d485074588a4f63455ec2627340bd6240c'

and it seems like babel plugins are not forwarded to craco test (it works for craco start)

I am experiencing the same thing where the babel plugin is not transforming code in test (on the 7.0.0-alpha.0 release). Below is the craco config.

module.exports = {
  babel: {
    plugins: ["styled-jsx/babel"],
  },
};

Here's the output

  console.error
    Warning: Received `true` for a non-boolean attribute `jsx`.
    
    If you want to write it to the DOM, pass a string instead: jsx="true" or jsx={value.toString()}.
        at style
        at div
        at App

      at printWarning (node_modules/react-dom/cjs/react-dom.development.js:67:30)
      at error (node_modules/react-dom/cjs/react-dom.development.js:43:5)
      at validateProperty$1 (node_modules/react-dom/cjs/react-dom.development.js:3521:9)
      at warnUnknownProperties (node_modules/react-dom/cjs/react-dom.development.js:3559:21)
      at validateProperties$2 (node_modules/react-dom/cjs/react-dom.development.js:3583:3)
      at validatePropertiesInDevelopment (node_modules/react-dom/cjs/react-dom.development.js:8765:5)
      at setInitialProperties (node_modules/react-dom/cjs/react-dom.development.js:9041:5)```

@yar2001
Copy link

yar2001 commented Jan 30, 2022

For tailwind user who using 7.0.0-alpha.0 and want to use postCSS, the following config is invalid:

   style: {
    postcss: {
      plugins: (plugins) => {
        return [
          'tailwindcss',
          ...plugins,
        ];
      },
      env: {
        stage: 3,
        features: {
          'hexadecimal-alpha-notation': true,
          'gap-properties': true,
          'color-functional-notation': true,
        },
      },
    },
  }

And I am using this config to achieve addon preset env:

  style: {
    postcss: {
      loaderOptions: (postcssLoaderOptions) => {
        postcssLoaderOptions.postcssOptions.plugins[2][1].features = {
          'hexadecimal-alpha-notation': true,
          'gap-properties': true,
          'color-functional-notation': true,
        };
        return postcssLoaderOptions;
      },
    },
  },

Relevant Code

https://github.com/gsoft-inc/craco/blob/4ea199b89b115fcb1306a725bf3edfc919d55404/packages/craco/lib/features/webpack/style/postcss.js#L41

https://github.com/facebook/create-react-app/blob/428ddb683193e548043a4a7edac73d2857386a4c/packages/react-scripts/config/webpack.config.js#L161

@100terres
Copy link

100terres commented Jan 30, 2022

@msieurmoustache Thank you 🙏 I'm using it to do Webpack aliases and the 7.0.0-alpha.0 version you've released works as expected 🎉

@patricklafrance
Copy link
Contributor Author

patricklafrance commented Jan 30, 2022

For tailwind user who using 7.0.0-alpha.0 and want to use postCSS, the following config is invalid:

   style: {
    postcss: {
      plugins: (plugins) => {
        return [
          'tailwindcss',
          ...plugins,
        ];
      },
      env: {
        stage: 3,
        features: {
          'hexadecimal-alpha-notation': true,
          'gap-properties': true,
          'color-functional-notation': true,
        },
      },
    },
  }

And I am using this config to achieve addon preset env:

  style: {
    postcss: {
      loaderOptions: (postcssLoaderOptions) => {
        postcssLoaderOptions.postcssOptions.plugins[2][1].features = {
          'hexadecimal-alpha-notation': true,
          'gap-properties': true,
          'color-functional-notation': true,
        };
        return postcssLoaderOptions;
      },
    },
  },

Relevant Code

https://github.com/gsoft-inc/craco/blob/4ea199b89b115fcb1306a725bf3edfc919d55404/packages/craco/lib/features/webpack/style/postcss.js#L41

https://github.com/facebook/create-react-app/blob/428ddb683193e548043a4a7edac73d2857386a4c/packages/react-scripts/config/webpack.config.js#L161

👌👌 Could you submit a PR with a recipe for tailwind?

@lkloeppel
Copy link

Hey!

I tried to use 7.0.0-alpha.0 with our latest config and I'm getting this error here:

TypeError: Cannot read property 'tap' of undefined
  - ExternalModuleFactoryPlugin.js:17 ExternalModuleFactoryPlugin.apply
    [test-ui]/[html-webpack-plugin]/[webpack]/lib/ExternalModuleFactoryPlugin.js:17:37
  
  - ExternalsPlugin.js:16 
    [test-ui]/[html-webpack-plugin]/[webpack]/lib/ExternalsPlugin.js:16:63
  
  - Hook.js:14 Hook.CALL_DELEGATE [as _call]
    [test-ui]/[webpack]/[tapable]/lib/Hook.js:14:14
  
  - Compiler.js:1097 
    [test-ui]/[webpack]/lib/Compiler.js:1097:23
  
  - Hook.js:18 Hook.CALL_ASYNC_DELEGATE [as _callAsync]
    [test-ui]/[webpack]/[tapable]/lib/Hook.js:18:14
  
  - Compiler.js:1094 Compiler.compile
    [test-ui]/[webpack]/lib/Compiler.js:1094:28
  
  - Compiler.js:543 Compiler.runAsChild
    [test-ui]/[webpack]/lib/Compiler.js:543:8
  
  - child-compiler.js:110 
    [test-ui]/[html-webpack-plugin]/lib/child-compiler.js:110:21

Our config is

const paths = require("react-scripts/config/paths");

const getClientEnvironment = require("react-scripts/config/env");

const shouldInlineRuntimeChunk = process.env.INLINE_RUNTIME_CHUNK !== "false";

module.exports = {
  webpack: {
    plugins: {
      remove:  [
            "HtmlWebpackPlugin",
            "InterpolateHtmlPlugin ",
            "InlineChunkHtmlPlugin",
          ],
      add:[
            new HtmlWebpackPlugin({
              inject: true,
              template: paths.appHtml,
              minify: {
                removeComments: true,
                collapseWhitespace: true,
                removeRedundantAttributes: true,
                useShortDoctype: true,
                removeEmptyAttributes: true,
                removeStyleLinkTypeAttributes: true,
                keepClosingSlash: true,
                minifyJS: true,
                minifyCSS: true,
                minifyURLs: true,
              },
            }),
            shouldInlineRuntimeChunk &&
            new InlineChunkHtmlPlugin(HtmlWebpackPlugin, [/runtime-.+[.]js/]),
            new InterpolateHtmlPlugin(
              HtmlWebpackPlugin,
              getClientEnvironment(paths.publicUrlOrPath.slice(0, -1)).raw
            ),
            new CspHtmlWebpackPlugin(cspPolicy, {
              hashEnabled: {
                'script-src': true,
                'style-src': true
              },
              nonceEnabled: {
                "style-src": false,
                "script-src": false,
              },
            })
          ]
    },
  },
};

The config is working without a problem with CRA 4 & craco 6.4.3.

We also tried to not remove / add the HtmlWebpackPlugin manually, but the CSP plugin is not getting correctly invoked and the CSP is not added to the index.html file - even with append added to the plugin config.

Just to ensure it's not the CspHtmlWebpackPlugin, I also tried

module.exports = {
  webpack: {
    plugins: {
      remove:  [
            "HtmlWebpackPlugin",
            "InterpolateHtmlPlugin ",
            "InlineChunkHtmlPlugin",
          ],
      add:[
            new HtmlWebpackPlugin({
              inject: true,
              template: paths.appHtml,
              minify: {
                removeComments: true,
                collapseWhitespace: true,
                removeRedundantAttributes: true,
                useShortDoctype: true,
                removeEmptyAttributes: true,
                removeStyleLinkTypeAttributes: true,
                keepClosingSlash: true,
                minifyJS: true,
                minifyCSS: true,
                minifyURLs: true,
              },
            }),
            shouldInlineRuntimeChunk &&
            new InlineChunkHtmlPlugin(HtmlWebpackPlugin, [/runtime-.+[.]js/]),
            new InterpolateHtmlPlugin(
              HtmlWebpackPlugin,
              getClientEnvironment(paths.publicUrlOrPath.slice(0, -1)).raw
            )
          ]
    },
  },
};

which shows the same error.

@EugeneSnikhovskiy
Copy link

Hello everyone.

Today I updated my app to craco: 7.0.0-alpha.0 + webpack: 5.67.0 + react-scripts: 5.0.0 and all works fine, but I get warnings for path alias in scss files.

My craco.config.js file:

const path = require('path');
const CracoAntDesignPlugin = require('craco-antd');
const CracoAlias = require('craco-alias');

module.exports = {
    eslintConfig: {
        enable: false
    },
    plugins: [
        {
            options: {
                source: 'options',
                baseUrl: './',
                aliases: {
                    "@components": './src/shared/components',
                    "@hooks": './src/shared/hooks',
                    "@services": './src/shared/services',
                    "@styles": './src/shared/styles',
                }
            },
            plugin: CracoAlias,
        },
        {
            options: {
                customizeThemeLessPath: path.join(
                    __dirname,
                    'src/shared/styles/variables.antd.less'
                )
            },
            plugin: CracoAntDesignPlugin,
        }
    ],
};

My .env file:

SASS_PATH=src/shared/styles
DISABLE_ESLINT_PLUGIN=true

My index.module.scss file:

@import 'variables';
@import 'mixins';
@import '../style.variables';

.title {
  font-size: 24px;
  line-height: 1.1em;
  color: $TM2Black;
}

And warning message is:

WARNING in ./src/shared/modules/modal/base/title/index.module.scss (./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[10].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[10].use[2]!./node_modules/resolve-url-loader/index.js??ruleSet[1].rules[1].oneOf[10].use[3]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[10].use[4]!./src/shared/modules/modal/base/title/index.module.scss)
Invalid dependencies have been reported by plugins or loaders for this module. All reported dependencies need to be absolute paths.
Invalid dependencies may lead to broken watching and caching.
As best effort we try to convert all invalid values to absolute paths and converting globs into context dependencies, but this is deprecated behavior.
Loaders: Pass absolute paths to this.addDependency (existing files), this.addMissingDependency (not existing files), and this.addContextDependency (directories).
Plugins: Pass absolute paths to fileDependencies (existing files), missingDependencies (not existing files), and contextDependencies (directories).
Globs: They are not supported. Pass absolute path to the directory as context dependencies.
The following invalid values have been reported:
 * "src/"
 * "src/shared"
 * "src/shared/styles"
 * and more ...
 @ ./src/shared/modules/modal/base/title/index.module.scss 8:6-446 22:17-24 26:7-21 58:25-39 59:36-47 59:50-64 63:6-73:7 64:54-65 64:68-82 70:42-53 70:56-70 72:21-28 83:0-416 83:0-416 84:22-29 84:33-47 84:50-64 61:4-74:5
 @ ./src/shared/modules/modal/base/title/index.tsx 9:0-36 29:26-33 35:17-23 42:28-37 42:49-59 55:28-35 59:19-29 84:26-32
 @ ./src/shared/modules/modal/index.ts 6:0-48 6:0-48
 @ ./src/shared/config/store/effects.tsx 31:0-49 142:21-36
 @ ./src/shared/config/core.ts 6:0-48 6:0-48
 @ ./src/bootstrap/index.tsx 21:0-47 33:21-52 34:10-30 35:10-30
 @ ./src/index.tsx 10:0-32 35:42-45

132 warnings have detailed information that is not shown.
Use 'stats.errorDetails: true' resp. '--stats-error-details' to show it.

webpack 5.67.0 compiled with 134 warnings in 1479 ms
No issues found.

With previous version of dependencies there are no any warnings like this. Can anyone help me please?

@EugeneSnikhovskiy
Copy link

Maybe someone it will be helpful. For now I ended up with temporary dirty solution in craco.config.js

const StyleAliasesFixPlugin = {
    overrideWebpackConfig: (data) => {
        const config = data.webpackConfig;
        const sassPath = process.env.SASS_PATH;
        if (!sassPath) {
            return config;
        }

        const options = data.pluginOptions;
        const aliases = options.aliases;
        const rules = config.module.rules[1];

        const locations = rules.oneOf.reduce((rulesAcc, rule, ruleIndex) => {
            const use = rule.use || [];
            const useIndex = use.findIndex(u => u.loader?.includes('sass-loader'));
            return (useIndex < 0) ? rulesAcc : {
                ...rulesAcc,
                [ruleIndex]: useIndex,
            };
        }, {});

        const resolvePathsOptions = {
            sassOptions: {
                importer: (alias) => {
                    if (aliases.includes(alias)) {
                        return {
                            file: path.join(__dirname, sassPath, `${alias}.scss`),
                        };
                    }
                    return null;
                },
            },
        };

        Object.entries(locations)
            .forEach(([ruleIndex, useIndex]) => rules.oneOf[+ruleIndex].use[useIndex].options = {
                ...rules.oneOf[+ruleIndex].use[useIndex].options,
                ...resolvePathsOptions
            });
        return config;
    },
};

module.exports = {
    // my config
    plugins: [
        // my other plugins. Note, StyleAliasesFixPlugin should be latest in order
        {
            options: {
                aliases: ['variables', 'mixins', 'spacing-mixins'],
            },
            plugin: StyleAliasesFixPlugin,
        },
    ],
};

@mousse-tache
Copy link

@lkloeppel, I'm trying to reproduce your issue with the same config, but to no avail. Do you have any other dependencies worth mentioning?

@patricklafrance
Copy link
Contributor Author

Hey!

I tried to use 7.0.0-alpha.0 with our latest config and I'm getting this error here:

TypeError: Cannot read property 'tap' of undefined
  - ExternalModuleFactoryPlugin.js:17 ExternalModuleFactoryPlugin.apply
    [test-ui]/[html-webpack-plugin]/[webpack]/lib/ExternalModuleFactoryPlugin.js:17:37
  
  - ExternalsPlugin.js:16 
    [test-ui]/[html-webpack-plugin]/[webpack]/lib/ExternalsPlugin.js:16:63
  
  - Hook.js:14 Hook.CALL_DELEGATE [as _call]
    [test-ui]/[webpack]/[tapable]/lib/Hook.js:14:14
  
  - Compiler.js:1097 
    [test-ui]/[webpack]/lib/Compiler.js:1097:23
  
  - Hook.js:18 Hook.CALL_ASYNC_DELEGATE [as _callAsync]
    [test-ui]/[webpack]/[tapable]/lib/Hook.js:18:14
  
  - Compiler.js:1094 Compiler.compile
    [test-ui]/[webpack]/lib/Compiler.js:1094:28
  
  - Compiler.js:543 Compiler.runAsChild
    [test-ui]/[webpack]/lib/Compiler.js:543:8
  
  - child-compiler.js:110 
    [test-ui]/[html-webpack-plugin]/lib/child-compiler.js:110:21

Our config is

const paths = require("react-scripts/config/paths");

const getClientEnvironment = require("react-scripts/config/env");

const shouldInlineRuntimeChunk = process.env.INLINE_RUNTIME_CHUNK !== "false";

module.exports = {
  webpack: {
    plugins: {
      remove:  [
            "HtmlWebpackPlugin",
            "InterpolateHtmlPlugin ",
            "InlineChunkHtmlPlugin",
          ],
      add:[
            new HtmlWebpackPlugin({
              inject: true,
              template: paths.appHtml,
              minify: {
                removeComments: true,
                collapseWhitespace: true,
                removeRedundantAttributes: true,
                useShortDoctype: true,
                removeEmptyAttributes: true,
                removeStyleLinkTypeAttributes: true,
                keepClosingSlash: true,
                minifyJS: true,
                minifyCSS: true,
                minifyURLs: true,
              },
            }),
            shouldInlineRuntimeChunk &&
            new InlineChunkHtmlPlugin(HtmlWebpackPlugin, [/runtime-.+[.]js/]),
            new InterpolateHtmlPlugin(
              HtmlWebpackPlugin,
              getClientEnvironment(paths.publicUrlOrPath.slice(0, -1)).raw
            ),
            new CspHtmlWebpackPlugin(cspPolicy, {
              hashEnabled: {
                'script-src': true,
                'style-src': true
              },
              nonceEnabled: {
                "style-src": false,
                "script-src": false,
              },
            })
          ]
    },
  },
};

The config is working without a problem with CRA 4 & craco 6.4.3.

We also tried to not remove / add the HtmlWebpackPlugin manually, but the CSP plugin is not getting correctly invoked and the CSP is not added to the index.html file - even with append added to the plugin config.

Just to ensure it's not the CspHtmlWebpackPlugin, I also tried

module.exports = {
  webpack: {
    plugins: {
      remove:  [
            "HtmlWebpackPlugin",
            "InterpolateHtmlPlugin ",
            "InlineChunkHtmlPlugin",
          ],
      add:[
            new HtmlWebpackPlugin({
              inject: true,
              template: paths.appHtml,
              minify: {
                removeComments: true,
                collapseWhitespace: true,
                removeRedundantAttributes: true,
                useShortDoctype: true,
                removeEmptyAttributes: true,
                removeStyleLinkTypeAttributes: true,
                keepClosingSlash: true,
                minifyJS: true,
                minifyCSS: true,
                minifyURLs: true,
              },
            }),
            shouldInlineRuntimeChunk &&
            new InlineChunkHtmlPlugin(HtmlWebpackPlugin, [/runtime-.+[.]js/]),
            new InterpolateHtmlPlugin(
              HtmlWebpackPlugin,
              getClientEnvironment(paths.publicUrlOrPath.slice(0, -1)).raw
            )
          ]
    },
  },
};

which shows the same error.

@lkloeppel I don't think this issue is related to CRACO. I think your plugins configuration doesn't work with the changes made by the CRA team to support Webpack 5.

This thread is only for issue related to CRACO to help us push a new release. If you want help form the community to migrate your config to Webpack 5 I suggest you open a new issue.

@patricklafrance
Copy link
Contributor Author

Not sure :(

Things haven't gone the way I hoped for.

At this point I don't even know if we will ever release v7. My role have changed and I don't have time (and motivation) anymore to work on CRACO. Since we are short staff, the management at GSoft won't assign anyone to this project.

We might also switch to next.js, still not sure... but if we do I don't see why the company would invest on this project.

If someone want to take over the project I'll hand it over to him/her.

@tomap
Copy link

tomap commented Apr 25, 2022

This is a sad news, but I understand.
Could you edit the readme to highlight the fact that you are looking for a new maintainer/ team of maintainers? Maybe create a "pinned" issue?

Thank you for the work you shared!

@nathanmmiller
Copy link

Maybe an unreasonable request/silly question but would it be possible to publish the alpha version as a full package with the caveat that some things don't work? My usage of craco is super simple - basically just overriding two small things on webpack config - and I believe I would still be able to benefit from the work that's been done even though there are other outstanding issues.

Alternatively, I'd be happy to contribute if there's a remaining "list of issues" that need to be attacked to make v7 a reality. Even if they aren't issues that would affect me.

@patricklafrance
Copy link
Contributor Author

@nathanmmiller I could BUT not every functionnalies would work. It might creates a lot of confusion and generate many issues. That is my main concern.

Most of the functionnalities works except the loader utilities which should be expended to support Webpack 5 asset modules.

Would be awesome if someone is willing to contribute. Ideally, this contribution would be part of some kind of leadership transition so I won't keep responsibility of reviewing & merging PR.

@xiaohaoo
Copy link

Why is it so slow to update the stable version to CRA 5?

@Rickyoung221
Copy link

Rickyoung221 commented Apr 30, 2022

I am trying to override the webpack plugin config, but it didn't succeed. I wonder is something wrong with my code? Or is it because it is not available in this version? (I am using CRA V5).

/* craco.config.js */
const path = require("path");
const rootPath = path.join(__dirname, "..");
const srcPath = path.join(rootPath, "src");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const webpack = require("webpack");
const { whenDev, whenProd, when } = require("@craco/craco");


module.exports = {
  alias: {},
  babel: {},
  webpack: {
    configure: (webpackConfig, { env, paths }) => {
      webpackConfig.entry = {
        main: [
          env === "development" &&
            require.resolve("react-dev-utils/webpackHotDevClient"),
          paths.appIndexJs,
        ].filter(Boolean),
        content: path.join(srcPath, "content_script", "index.tsx"),
        background: path.join(srcPath, "background_script", "index.tsx"),
      };
      webpackConfig.output = {
        ...webpackConfig.output,
        ...{
          filename: "static/js/[name].js",
        },
      };

      //webpackConfig.devtool = false,

      webpackConfig.optimization = {
        ...webpackConfig.optimization,
        ...{
          runtimeChunk: false,
        },
      };
//Override the webpack config plugin.
      webpackConfig.plugins.map((plugin) => {
        if (plugin instanceof HtmlWebpackPlugin) {
          if (plugin.options) {
            Object.assign(plugin.options, {
              inject: true,
              chunks: ["main", "background"],
              template: path.resolve(__dirname, "../public/index.html"),
              filename: "popup.html",
            });
          }
        }

        return plugin;
      });

      return webpackConfig;
    },
   
  },
};

So I am trying to modify the default output index.html to popup.html, but nothing happened with this code. Can anyone helps? Thanks in advance.

@nathanmmiller
Copy link

Most of the functionnalities works except the loader utilities which should be expended to support Webpack 5 asset modules.

Is there some kind of "how to reproduce" or associated issue with this such that I could play around with it and see if I can find/contribute a solution?

@Spaubleit
Copy link

I have a little advice for people struggling with craco or other similar tool. If you use yarn package manager, you can patch react-scripts configs directly with "yarn patch" command. I switched to this approach in 2 projects. Hope this will help someone.

@SentretC
Copy link

A tip for newcomers like me: to create a project compatible with craco as of now, use npx create-react-app my-app --scripts-version 4.0.3 (npx create-react-app@4.0.3 my-app won't work).

@SentretC
Copy link

Then I got an invisible iframe blocking interaction and the error 'process is not defined' on hot reload. I solved it following the 'If the error is not resolved' part of this blog. I think I should mention it here to help others.

NiGhTTraX added a commit to NiGhTTraX/ts-monorepo that referenced this issue May 15, 2022
@rlchandani
Copy link

@Rickyoung221

Here is your solution, I tested it locally and it should be working.

plugins: [
  ...webpackConfig.plugins.map((plugin) => {
    if (plugin instanceof HtmlWebpackPlugin) {
      if (plugin.userOptions.template?.endsWith("index.html")) {
        Object.assign(plugin.userOptions, {
          filename: "popup.html",
        });
      }
    }
    return plugin;
  }),
],

@tomer-dev
Copy link

tomer-dev commented May 28, 2022

I have a little advice for people struggling with craco or other similar tool. If you use yarn package manager, you can patch react-scripts configs directly with "yarn patch" command. I switched to this approach in 2 projects. Hope this will help someone.

Thank you for the suggestion! For something as small as a couple of alias lines, that makes total sense to me.

And thank you Craco maintainers and collaborators for doing this work! I totally get that Next.js is a better alternative for CRA in general.

For those who work with CRA - take note that CRA (specifically the React-Scripts bundle) maintainers themselves do not intend to focus on the project either.. So if you care about upgrading to CRA5 and have some serious Webpack tweaks:

  • See if forking React-Scripts directly makes sense (or patching the project as quoted above for small/medium tweaks)
  • Wait for updates from CRACO with no expectations - this is an open-source community
  • Migrate from CRA for a better alternative in the long term - Vite and Next.js among others

@tomer-dev
Copy link

CRA is moving to maintenance mode
facebook/create-react-app#11180 (comment)

@popuguytheparrot
Copy link

CRA is moving to maintenance mode facebook/create-react-app#11180 (comment)

1 year ago post

@mattsputnikdigital
Copy link

CRA is moving to maintenance mode facebook/create-react-app#11180 (comment)

1 year ago post

Yeah that's what I took from it, they are adding no more features, just keeping it alive. As long as React recommends CRA then I don't think they are abandoning it.

@totszwai
Copy link

totszwai commented Jul 7, 2022

Anybody here seen this error and know what do I need to change in the craco.config.js to fix this? I tried alpha.7 but didn't fix it. I just upgraded all of my dependencies to React 18, Webpack 5 etc. and faced this.

Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
 - configuration.optimization has an unknown property 'namedChunks'. These properties are valid:
   object { checkWasmTypes?, chunkIds?, concatenateModules?, emitOnErrors?, flagIncludedChunks?, innerGraph?, mangleExports?, mangleWasmImports?, mergeDuplicateChunks?, minimize?, minimizer?, moduleIds?, noEmitOnErrors?, nodeEnv?, portableRecords?, providedExports?, realContentHash?, removeAvailableModules?, removeEmptyChunks?, runtimeChunk?, sideEffects?, splitChunks?, usedExports? }
   -> Enables/Disables integrated optimizations.
   Did you mean optimization.chunkIds: "named" (BREAKING CHANGE since webpack 5)?


ERROR: "craco" exited with 1.

@dilanx
Copy link
Owner

dilanx commented Jul 7, 2022

That looks like a configuration error with webpack and not with craco specifically @totszwai. I assume you're doing something like namedChunks: true somewhere in your config, but it looks like webpack 5 requires you to use chunkIds: 'named' instead (as indicated by the error you received).

@dilanx
Copy link
Owner

dilanx commented Jul 7, 2022

Also, for organizational purposes, I'm locking this issue. If anyone has any issues with anything craco related, feel free to create a new issue!

Repository owner locked and limited conversation to collaborators Jul 7, 2022
@dilanx dilanx removed the todo label Oct 2, 2022
@dilanx
Copy link
Owner

dilanx commented Oct 2, 2022

Discussion is now at #426.

@dilanx dilanx closed this as not planned Won't fix, can't repro, duplicate, stale Oct 2, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests