dilanx / craco

Create React App Configuration Override, an easy and comprehensible configuration layer for Create React App.
https://craco.js.org
Apache License 2.0
7.44k stars 499 forks source link

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

Closed patricklafrance closed 2 years ago

patricklafrance commented 2 years ago

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: https://github.com/gsoft-inc/craco/issues/377 https://github.com/gsoft-inc/craco/issues/353 https://github.com/gsoft-inc/craco/issues/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 commented 2 years ago

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 commented 2 years ago

maybe milestone or something else for progress?

olso commented 2 years ago

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 7aab18d485074588a4f63455ec2627340bd6240c

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

mousse-tache commented 2 years ago

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

Cheers

olivierbeaulieu commented 2 years ago

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 commented 2 years ago

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 commented 2 years ago

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 commented 2 years ago

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

patricklafrance commented 2 years ago

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 commented 2 years ago

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 commented 2 years ago

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 commented 2 years ago

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 commented 2 years ago

@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 commented 2 years ago

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 commented 2 years ago

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 Your error seem to be related to the usage of 2 plugins, not the core features of CRACO. This thread is only for issue related to CRACO to help us push a new release.

If you need help with the plugins, I suggest you open an issue on the plugins repository instead.

m-s7 commented 2 years ago

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

Hi,

~~I'm also using 7.0.0-alpha.0 and aliases works fine, but I can't get them to work with jest. I tried every configuration I found and no matter, what every test is failed because Cannot find module... error. Could you maybe check in your project if jest is working with 7.0.0.-alpha.0?~~

I was finally able to get it to work using craco-alias, now everything works fine :)

lkloeppel commented 2 years ago

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

@msieurmoustache That was a good hint! I debugged through the libraries and it seems like craco is not working with @storybook/react.

My guess is that the problems comes from @storybook/react still using webpack 4 which probably causes a conflict in loading webpack 4 for executing the craco script. If I set "@storybook/**/webpack": "^5.0.0" in the resolutions the error is gone and it's working again (But storybook stops working πŸ˜… )

@patricklafrance I get your point - but I think this is not a webpack / plugin problem. I did two tests:

patricklafrance commented 2 years ago

@lkloeppel got it.

Do you have any idea about what could be the problem with CRACO for your setup?

lkloeppel commented 2 years ago

@lkloeppel got it.

Do you have any idea about what could be the problem with CRACO for your setup?

@patricklafrance I created a local fork of craco and will do some investigations over the next days! But it definitely has to do with some problems which webpack version is used to to the build / start.

patricklafrance commented 2 years ago

@lkloeppel got it. Do you have any idea about what could be the problem with CRACO for your setup?

@patricklafrance I created a local fork of craco and will do some investigations over the next days! But it definitely has to do with some problems which webpack version is used to to the build / start.

@lkloeppel Awesome, let us know what you find :)

lkloeppel commented 2 years ago

@patricklafrance I solved the issue!

While debugging I compared the initial webpack config and the override config and found something interesting about the HtmlWebpackPlugin.

Before:

  HtmlWebpackPlugin { 
     userOptions: [Object], 
     version: 5 
  },

After:

 HtmlWebpackPlugin {
      options: [Object],
      childCompilerHash: undefined,
      assetJson: undefined,
      hash: undefined,
      version: 4
    },

So it seems that the added plugin through my config was version 4 of the html-webpack-plugin rather than version 5 used by react-scripts.

The problem here is, that react-scripts has the dependency of version 5 whereas @storybook/react has the dependency of version 4 and as I didn't add html-webpack-plugin directly to my package.json, it picked the storybook version rather than the react-scripts version during the build job - which then led to the error posted.

After adding "html-webpack-plugin": "5.5.0" directly to my package.json, the failure was gone and the build was successful.

This error itself has nothing to do with CRACO and is one of the weird effects of npm / yarn.

But I think it might be worth adding a section in the FAQs or the troubleshooting to always add all dependencies used in craco.config.js directly in the package.json rather than relying on the react-scripts dependencies. (which in general is a thing developers should do πŸ˜… )

patricklafrance commented 2 years ago

@patricklafrance I solved the issue!

While debugging I compared the initial webpack config and the override config and found something interesting about the HtmlWebpackPlugin.

Before:

  HtmlWebpackPlugin { 
     userOptions: [Object], 
     version: 5 
  },

After:

 HtmlWebpackPlugin {
      options: [Object],
      childCompilerHash: undefined,
      assetJson: undefined,
      hash: undefined,
      version: 4
    },

So it seems that the added plugin through my config was version 4 of the html-webpack-plugin rather than version 5 used by react-scripts.

The problem here is, that react-scripts has the dependency of version 5 whereas @storybook/react has the dependency of version 4 and as I didn't add html-webpack-plugin directly to my package.json, it picked the storybook version rather than the react-scripts version during the build job - which then led to the error posted.

After adding "html-webpack-plugin": "5.5.0" directly to my package.json, the failure was gone and the build was successful.

This error itself has nothing to do with CRACO and is one of the weird effects of npm / yarn.

But I think it might be worth adding a section in the FAQs or the troubleshooting to always add all dependencies used in craco.config.js directly in the package.json rather than relying on the react-scripts dependencies. (which in general is a thing developers should do πŸ˜… )

@lkloeppel yeah that’s a good tip :)

jamesyoung1337 commented 2 years ago

How do I use a local version of craco? I have installed craco 7.0.0.alpha.0 and I have this error:

> demo-app@0.1.0 start
> craco start --verbose

sh: 1: craco: not found

If I try to run craco from the node_modules directory,

node:internal/modules/cjs/loader:936
  throw err;
  ^

Error: Cannot find module 'cosmiconfig-typescript-loader'
Require stack:

[snip]

If I go down that road by installing this package (then it requires merge from webpack merge) I have issues with merge not being a function.

Can anyone throw some light on testing craco 7.0.0?

Thanks,

patricklafrance commented 2 years ago

Released https://github.com/gsoft-inc/craco/releases/tag/v7.0.0-alpha.3 to fix issue with Jest.

Sorry for the versioning mess, I had an issue while releasing and it took a while for the new released version to appear in NPM. I though something failed πŸ˜…

zavan commented 2 years ago

The only way I was able to make tailwind 3.0 with a custom config file path to work was:

module.exports = {
  style: {
    postcss: {
      loaderOptions: (postcssLoaderOptions) => {
        postcssLoaderOptions.postcssOptions.plugins = [
          require('postcss-import'),
          require('tailwindcss/nesting'),
          require('tailwindcss')('./src/css/tailwind.config.js'),
          'postcss-flexbugs-fixes',
          [
            'postcss-preset-env',
            {
              autoprefixer: {
                flexbox: 'no-2009',
              },
              stage: 3,
            },
          ],
        ];

        return postcssLoaderOptions;
      },
    },
  },
};

Copied and customized from https://github.com/facebook/create-react-app/blob/9673858a3715287c40aef9e800c431c7d45c05a2/packages/react-scripts/config/webpack.config.js#L161-L173

Also see: https://github.com/facebook/create-react-app/issues/11920#issuecomment-1012513065

patricklafrance commented 2 years ago

Hi @zavan,

What version of CRACO are you using?

zavan commented 2 years ago

@patricklafrance I'm using v7.0.0-alpha.3 with react-scripts v5.0.0 and tailwind v3.0.23.

patricklafrance commented 2 years ago

Thanks @zavan , will have a look.

TheNuclearNexus commented 2 years ago

I'm having an issue where tailwind is interfering with my existing React styling. With Tailwind image Without Tailwind image

Using craco 7.0.0-alpha.3 and tailwind 3.0.23. Currently using the craco.config.js that zavan posted

honungsburk commented 2 years ago

I'm trying to load a wasm package using craco 7.0.0-alpha.3, react.scripts 5.0.0, and wasm-loader 1.3.0 The library I'm trying to load is @emurgo/cardano-serialization-lib-browser 10.0.4

Config:

const { addBeforeLoader, loaderByName } = require('@craco/craco');
const path = require('path');
const fileSystem = require('fs-extra');

module.exports = {
  webpack: {
    configure: (webpackConfig) => {
      const wasmExtensionRegExp = /\.wasm$/;
      webpackConfig.resolve.extensions.push('.wasm');

      webpackConfig.module.rules.forEach((rule) => {
        (rule.oneOf || []).forEach((oneOf) => {
          if (oneOf.loader && oneOf.loader.indexOf('file-loader') >= 0) {
            oneOf.exclude.push(wasmExtensionRegExp);
          }
        });
      });

      const wasmLoader = {
        test: /\.wasm$/,
        exclude: /node_modules/,
        loaders: ['wasm-loader'],
      };

      addBeforeLoader(webpackConfig, loaderByName('file-loader'), wasmLoader);
      return webpackConfig;
    },
  },
};

But I get this error:

> atomic-swap@1.6.0 start-basic
> craco start

Failed to compile.

Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
 - configuration.module.rules[1] should be one of these:
   ["..." | object { assert?, compiler?, dependency?, descriptionData?, enforce?, exclude?, generator?, include?, issuer?, issuerLayer?, layer?, loader?, mimetype?, oneOf?, options?, parser?, realResource?, resolve?, resource?, resourceFragment?, resourceQuery?, rules?, scheme?, sideEffects?, test?, type?, use? }, ...]
   -> A rule.
   Details:
    * configuration.module.rules[1].oneOf[2].use[1] has an unknown property 'test'. These properties are valid:
      object { ident?, loader?, options? }
    * configuration.module.rules[1].oneOf[2].use[1] has an unknown property 'exclude'. These properties are valid:
      object { ident?, loader?, options? }
    * configuration.module.rules[1].oneOf[2].use[1] has an unknown property 'loaders'. These properties are valid:
      object { ident?, loader?, options? }

it seems like it thinks I should be using this type from webpack:

    interface RuleSetLoader {
        /**
         * Loader name
         */
        loader?: string | undefined;
        /**
         * Loader options
         */
        options?: RuleSetQuery | undefined;
        /**
         * Unique loader identifier
         */
        ident?: string | undefined;
        /**
         * Loader query
         */
        query?: RuleSetQuery | undefined;
    }

The config file is working fine in CRA 4 with craco 6.4.3, and wasm-loader 1.3.0

alexisdray commented 2 years ago

@honungsburk were you able to find a workaround for your issue?

i'm facing more or less the same problem:

const overrideWebpackConfig = ({webpackConfig, pluginOptions, context: {paths},}) => {
  const loader = require.resolve("graphql-tag/loader");
  const test = (pluginOptions && pluginOptions.test) || /\.(graphql|gql)$/;
  const exclude = (pluginOptions && pluginOptions.exclude) || /node_modules/;

  addBeforeLoader(webpackConfig, loaderByName("file-loader"), {
    test,
    loader,
    exclude,
  });

  return webpackConfig;
};

// module.exports = { overrideWebpackConfig };
module.exports = {
  eslint: {
    enable: false
  },
  typescript: {
    isolatedModules: false
  },
  plugins: [
    {
      plugin: {
        overrideWebpackConfig
      }
    },
    {
      plugin: CracoEsbuildPlugin,

which gives:

Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
 - configuration.module.rules[1] should be one of these:
   ["..." | object { assert?, compiler?, dependency?, descriptionData?, enforce?, exclude?, generator?, include?, issuer?, issuerLayer?, layer?, loader?, mimetype?, oneOf?, options?, parser?, realResource?, resolve?, resource?, resourceFragment?, resourceQuery?, rules?, scheme?, sideEffects?, test?, type?, use? }, ...]
   -> A rule.
   Details:
    * configuration.module.rules[1].oneOf[2].use[1] has an unknown property 'test'. These properties are valid:
      object { ident?, loader?, options? }
    * configuration.module.rules[1].oneOf[2].use[1] has an unknown property 'exclude'. These properties are valid:
      object { ident?, loader?, options? }

seems specific to file-loader as well, esbuild-loader for example does not produce this error even when newLoader has same object properties.

honungsburk commented 2 years ago

@alexisdray I migrated to Vite using this library to load the wasm.

patricklafrance commented 2 years ago

Hey @honungsburk and @alexisdray

Yeah we aware of this issue, the last thing to support before releasing a new version is to adapt CRACO loader helpers to Asset Modules.

I am not sure when we will be able to do it though, PR welcome if someone is willing to do it!

ionnikovv commented 2 years ago

Hello everyone! Is there are any changes for the craco.config.js especially for CRA 5?

mattsputnikdigital commented 2 years ago

@lkloeppel why do you unload HtmlWebpackPlugin and then load it again with the defaults? If you leave that step out a CPS still gets added to the html.

lkloeppel commented 2 years ago

@lkloeppel why do you unload HtmlWebpackPlugin and then load it again with the defaults? If you leave that step out a CPS still gets added to the html.

@mattsputnikdigital It did not with CRA 4, we tried everything, but plugins which were depending on the HtmlWebpackPlugin did only work if we removed and added the HtmlWebpackPlugin again with defaults. (We tried to prepend / append them etc.).

But I'll try again with CRA 5

Pika-Pool commented 2 years ago

Please pin this issue in the issues tab so new CRA5 issues are not created unnecessarily

PaulWagener commented 2 years ago

I also had issues with getting craco-raw-loader working with Craco 7.0.0 The workaround/hack that I created utilizes the Asset Module system:

const config = {
  plugins: [
    {
      plugin: {
        overrideWebpackConfig: ({ webpackConfig }) => {
          webpackConfig.module.rules[1].oneOf.unshift({
            test: /\.glsl$/,
            type: "asset/source",
          });

          return webpackConfig;
        },
      },
    },
  ],
};

export default config;
flyingcrp commented 2 years ago

When will the official version of v7 be released?

patricklafrance commented 2 years ago

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 commented 2 years ago

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 commented 2 years ago

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 commented 2 years ago

@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 commented 2 years ago

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

Rickyoung221 commented 2 years ago

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 commented 2 years ago

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 commented 2 years ago

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 commented 2 years ago

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 commented 2 years ago

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.

rlchandani commented 2 years ago

@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;
  }),
],