reactjsreact-contextvitetsclerna

React context missing in Vite monorepo


I'm trying to switch my lerna monorepo over from create-react-app to vite. My repo structure is roughly:

- packages
  - shared
    - useSomeHook.ts
    - useSomeHook2.ts
  - app1
    - SomeConsumer.tsx

useSomeHook wraps a 3rd party hook (redux's useSelector) and returns some values. useSelector requires being called down the tree from a redux store context provider. I have Storybook setup with a redux decorator in the shared package and I verified that useSomeHook is working when used in the shared package. The issue is when I import and use useSomeHook in SomeConsumer.tsx in app1, the redux context is now undefined.

I am 100% absolutely certain that it is being called within the redux provider in app1. All of the bare calls of useSelector in app1 are working as intended, it's exclusively on this hook that I'm importing from my shared package.

I also have useSomeHook2 that wraps a different 3rd party hook that also relies on context (react-router's useHistory) that's displaying the same problem. There was no issue when the shared package was bundled with tsc. I think the main difference is that tsc was outputting commonjs while vite is outputting esm, but I have no idea where to start debugging.


Solution

  • My mistake was not using the rollup.externals array. The shared hooks where trying to consume a context from the shared package instead of where they were being called in app1. My understanding is that the externals array fixes this resolution