vite-plugin-federation icon indicating copy to clipboard operation
vite-plugin-federation copied to clipboard

React TypeError: Cannot read properties of null (reading 'useState')

Open guoxiaxing opened this issue 3 years ago • 85 comments

Versions

  • vite-plugin-federation: 1.1.10
  • vite: 3.2.3

Reproduction

Additional Details

clone this repo https://github.com/guoxiaxing/vite-FM, cd into each directory and run pnpm install. cd remote directory and run pnpm build && npx vite preview --port=3001 --strictPort, then cd host directory and run pnpm run dev.

Steps to reproduce

above

What is Expected?

all working

What is actually happening?

but http://localhost:5173/ not work, and throw Uncaught TypeError: Cannot read properties of null (reading 'useState') at react_production_min.useState image

guoxiaxing avatar Nov 29 '22 06:11 guoxiaxing

遇到同样的问题了,请问有解决吗

Yulingsong avatar Dec 22 '22 08:12 Yulingsong

the same. It looks no bad until importing react. the examples don't consist of any react imports

Rudel-git avatar Dec 26 '22 16:12 Rudel-git

Please try to upgrade to vite 4.0 & @originjs/vite-plugin-federation ^1.1.13

image

flyfishzy avatar Jan 14 '23 09:01 flyfishzy

host: dev remote: preview shared: ['react', 'react-dom']

Versions

  • "@originjs/vite-plugin-federation": "^1.1.13",
  • "vite": "^4.0.4",
  • "@vitejs/plugin-react": "^3.0.1",
  • "react": "^18.2.0",
  • "react-dom": "^18.2.0"

updated and now got. reactexports is undefined, default has the value

image image image

Rudel-git avatar Jan 14 '23 11:01 Rudel-git

host: dev remote: preview shared: ['react', 'react-dom']

Versions

  • "@originjs/vite-plugin-federation": "^1.1.13",
  • "vite": "^4.0.4",
  • "@vitejs/plugin-react": "^3.0.1",
  • "react": "^18.2.0",
  • "react-dom": "^18.2.0"

updated and now got. reactexports is undefined, default has the value

image image image

@RudikS-git , @flyfishzy same problem, do you have any update about this?

toanil315 avatar Jan 15 '23 10:01 toanil315

Can you provide a reproduction repo? @RudikS-git @toanil315

flyfishzy avatar Jan 16 '23 02:01 flyfishzy

I created a reproduction for the original error with updated versions here: https://github.com/TimKolberger/issue-reproduction-vite-federated-modules

I prepared the repo be easy to setup:

git clone [email protected]:TimKolberger/issue-reproduction-vite-federated-modules.git repro-issue-294 \
  && cd $_ \
  && pnpm install \
  && pnpm build \
  && pnpm preview

Error

Cannot read properties of null (reading 'useState')

image

_federation_shared_ is registered, but not used:

image

Versions in host and remote project:

  "dependencies": {
    "react": "18.2.0",
    "react-dom": "18.2.0",
    ...
  },
  "devDependencies": {
    "@originjs/vite-plugin-federation": "1.1.14",
    "@vitejs/plugin-react": "3.0.1",
    "vite": "4.0.4",
    ...
  }

Host vite.config.ts: https://github.com/TimKolberger/issue-reproduction-vite-federated-modules/blob/main/packages/host/vite.config.ts

Remote vite.config.ts: https://github.com/TimKolberger/issue-reproduction-vite-federated-modules/blob/main/packages/widget/vite.config.ts

TimKolberger avatar Jan 22 '23 15:01 TimKolberger

I have the same issue. Any ideas on how to quickly fix it?

0ro avatar Jan 23 '23 13:01 0ro

I have the same issue. Any ideas on how to quickly fix it?

I'm joining to the question . I just switch from create-react-app to vite and really love it. don't want to switch to webpack just to use webapack Module federation plugin

chiffenok avatar Jan 23 '23 16:01 chiffenok

I have the same issue. Any ideas on how to quickly fix it?

If you just want to run it, so delete line shared: ['react', 'react-dom'], it work for me. Waiting for @flyfishzy fix it The error happened to me was vite shared create 2 instance of react and this cause error

toanil315 avatar Jan 23 '23 16:01 toanil315

If you just want to run it, so delete line shared: ['react', 'react-dom'], it work for me. Waiting for @flyfishzy fix it The error happened to me was vite shared create 2 instance of react and this cause error

It still doesn't work I have a host application with React and two remotes with the same React version. I already tried a lot of combinations with shared options and no one works. @flyfishzy you are only my hope, I don't want to go back to CRA

0ro avatar Jan 23 '23 17:01 0ro

I have the same problem when using ant design. I also tried everything, nothing helps.

When I add the ant design component, an error appears: Uncaught TypeError: Cannot read properties of null (reading 'useContext')

Sergey-Makkoev avatar Jan 28 '23 12:01 Sergey-Makkoev

@flyfishzy wrote:

Can you provide a reproduction repo? @RudikS-git @toanil315

@flyfishzy you can break the existing example "react-vite" in this repo just by adding "const [ state ] = React.useState(0);" to the Button.jsx. You don't even have to use the state variable anywhere.

Here is the full modified Button.jsx file:

    import React from "react";
    import "./Button.css";

    export default ({caption = "Shared Button"}) => {
        const [ state ] = React.useState(0);

        return (
            <button className='shared-btn'>{caption}</button>
        )
   }

I am in the same boat as everyone else. I love Vite and need module federation and don't want to go back to webpack. Please advise. Thank you.

mndbndr avatar Jan 28 '23 20:01 mndbndr

Hello @flyfishzy I see that You picked up this issue few days ago, thats great! I just wanted to highlight that the same issue (but different error) applies to react 17. React is throwing error https://reactjs.org/docs/error-decoder.html/?invariant=321 but from what I've noticed, it appears that react instance is also equal to null (same problem as react 18).

There are two minimal repos with reproduced issue. Notice that I also want to consume module inside of worker file. This is something that is not working in webpack, but it does in vite 🎆

https://github.com/grzesiek-ds/vite-host https://github.com/grzesiek-ds/vite-module

grzesiek-ds avatar Jan 31 '23 10:01 grzesiek-ds

Hello, I actually have the same problem with Vite 4. The problem does not occur with Vite 2.8. I see that work is in progress on it but I wanted to know what you advise. We have a rather urgent need to share a module present in a Vite config and to use it in a Webpack config. Do you recommend leaving Vite for now?

rastiben avatar Feb 01 '23 08:02 rastiben

Hello, I actually have the same problem with Vite 4. The problem does not occur with Vite 2.8. I see that work is in progress on it but I wanted to know what you advise. We have a rather urgent need to share a module present in a Vite config and to use it in a Webpack config. Do you recommend leaving Vite for now?

@rastiben for me it's not working with Vite 2.8 neither (( Do you maybe have reproduction code?

chiffenok avatar Feb 08 '23 16:02 chiffenok

We have released a new version v1.2.0, please try this version and check if the problem is fixed.

flyfishzy avatar Feb 11 '23 03:02 flyfishzy

I confirm that it works perfectly! Thank you very much for the work!

rastiben avatar Feb 11 '23 09:02 rastiben

I updated to version 1.2. But I have the same error. As soon as a component from antd appears in the remote project, an error appears: Cannot read properties of null (reading 'useState').

https://github.com/Sergey-Makkoev/vite-antDesign

8

Sergey-Makkoev avatar Feb 11 '23 10:02 Sergey-Makkoev

Same error here,cann't use useState in shared component, any idea about this?

ytftianwen avatar Feb 13 '23 11:02 ytftianwen

Same error here,can't use useState in shared component, any idea about this?

For me, it seems to work so far. Maybe try to make sure that the package really updated? I mean I needed to remove /node_modules and yarn.lock because the old version was cached

chiffenok avatar Feb 13 '23 11:02 chiffenok

Same error here,can't use useState in shared component, any idea about this?

For me, it seems to work so far. Maybe try to make sure that the package really updated? I mean I needed to remove /node_modules and yarn.lock because the old version was cached

Year, it works finally, thks~

ytftianwen avatar Feb 14 '23 02:02 ytftianwen

@flyfishzy Update fixes the issue with shared react instance, but unfortunately it brings another issue. Right now, it's not possible to consume federated module inside of web worker script.

In addition to that, inside of federated module, it's not possible to destructure import like import { useState } from 'react', we have to import React from 'react'.

In example repositories, I've updated both vite and @originjs/vite-plugin-federation to latests versions. Simply npm/yarn install and then run build and preview scripts.

https://github.com/grzesiek-ds/vite-host https://github.com/grzesiek-ds/vite-module

error while building host: image

host config:

import { defineConfig } from 'vite';
import federation from '@originjs/vite-plugin-federation';
import react from '@vitejs/plugin-react';
import { dependencies } from './package.json';

export default defineConfig({
  build: {
    target: 'esnext'
  },
  worker: {
    format: 'es',
  },
  server: {
    port: 3005,
  },
  plugins: [
    react(),
    federation({
      name: 'host',
      remotes: {
        myModule: 'http://localhost:3008/assets/remoteEntry.js',
      },
      shared: {
        react: {
          version: dependencies.react,
          requiredVersion: dependencies.react,
        },
        'react-dom': {
          version: dependencies['react-dom'],
          requiredVersion: dependencies['react-dom'],
        },
      },
    }),
  ],
});

module config:

export default defineConfig({
  build: {
    target: 'esnext'
  },
  preview: {
    host: 'localhost',
    port: 3008,
    strictPort: true,
    headers: {
      'Access-Control-Allow-Origin': '*',
    },
  },
  plugins: [
    react(),
    federation({
      name: 'myModule',
      filename: 'remoteEntry.js',
      exposes: {
        './testValue': './src/testValue',
        './WithoutState': './src/WithoutState',
        './WithState': './src/WithState',
      },
      shared: {
        react: {
          generate: false,
          version: dependencies.react,
          requiredVersion: dependencies.react,
        },
      },
    }),
  ],
});

grzesiek-ds avatar Feb 14 '23 10:02 grzesiek-ds

I updated to version 1.2. But I have the same error. As soon as a component from antd appears in the remote project, an error appears: Cannot read properties of null (reading 'useState').

Sergey-Makkoev/vite-antDesign

8

@Sergey-Makkoev I tried your project and I have a question, why do I need to exposes itself and then refer to it after? After I changed some of the code I got this screen. Comment out the remotes app to replace it with a local reference

 remotes: {
        // app: 'http://localhost:5001/assets/remoteEntry.js',
        shared: 'http://localhost:5000/assets/shared.js',
      },

image

Jiannan-dev avatar Feb 18 '23 09:02 Jiannan-dev

Experiencing this issue still, with following dependencies in both remote & host:

"@originjs/vite-plugin-federation": "^1.2.2", "@vitejs/plugin-react": "^4.0.0", "vite": "^4.3.2", "react": "^18.2.0", "react-dom": "^18.2.0"

removed node_modules, package-lock & re-installed deps but still no luck.

Running on node 16.15.0 & npm 8.5.5, macOS

vileppanen avatar Apr 26 '23 06:04 vileppanen

Experiencing this issue still, with following dependencies in both remote & host:

"@originjs/vite-plugin-federation": "^1.2.2", "@vitejs/plugin-react": "^4.0.0", "vite": "^4.3.2", "react": "^18.2.0", "react-dom": "^18.2.0"

removed node_modules, package-lock & re-installed deps but still no luck.

Running on node 16.15.0 & npm 8.5.5, macOS

Dug little deeper, and it seems that in my case, everything works fine in version 1.1.14. When upgrading to 1.2.0, the errors start occurring.

So, If I'm not totally offset, there's something in these changes that introduce some breaking change: https://github.com/originjs/vite-plugin-federation/compare/99c44e40e129185cfd3cd0a0984244ad71a09941...e78a42e4c68f634633cf8b0620199c5ed12f5267

vileppanen avatar Apr 26 '23 18:04 vileppanen

Stumbled on the same problem as @vileppanen same solution also worked for me. I am in the process of migrating a rather large cra/craco/mf setup so I can't really pinpoint the exact issue. The downgrade worked fine, will try to do some investigation later if this keeps being a problem.

dawidcxx avatar May 10 '23 16:05 dawidcxx

I ran into the same problem, for some reason when I define shared modules on the remote side

shared: {
  react: {
    requiredVersion: '^18.2.0',
    version: '^18.2.0',
  },
  'react-dom': {
    requiredVersion: '^18.2.0',
    version: '^18.2.0',
  },
},

will not work, but

shared: ['react', 'react-dom']

works

wenyichen avatar May 11 '23 20:05 wenyichen

I was running into this exact error when trying to run multiple remote react as apps in a host, this is my setup here: https://github.com/sumcoding/react-in-vue which should be all up to date on versions as recommended here.

I am attempting to pull in the react apps in a bit of a different way then the react-in-vue example does, using v-html is not an option for me, also needing react as a dependency of the host is something I would also like to avoid.

I was able to get rid of the actual error by destructuring react-dom/client as the latest react docs recommend

from this

import App from "./App";
import ReactDOM from "react-dom";


const mount = (el) => {
  ReactDOM.createRoot(el).render(<App />);
}
export { mount }

to this

import App from "./App";
import { createRoot } from "react-dom/client";

const mount = (el, identifierPrefix = 'react-app-two') => {
  const root = createRoot(el, { identifierPrefix })
  root.render(<App />);
}

export { mount }

And that appeared to work at first, but what it seems to have actually done is caused the bundler to not externalize react-dom as it was previously and so when I have multiple react apps I also load in multiple react-dom's

image

"react": "^18.2.0", "react-dom": "^18.2.0", "vue": "^3.3.4", "@originjs/vite-plugin-federation": "^1.2.3", "@vitejs/plugin-react": "^4.0.0", "@vitejs/plugin-vue": "^4.2.3", "vite": "^4.3.9"

sumcoding avatar Jun 06 '23 12:06 sumcoding

Same issue here when trying to import a React component and sadly none of the workarounds seem to fix it for me.

react: 18.2.0
vite: 4.3.9
@originjs/vite-plugin-federation: 1.2.3

dworzycp avatar Jun 27 '23 09:06 dworzycp