jotaijs / jotai-devtools

A powerful toolkit to enhance your development experience with Jotai
https://jotai.org/docs/tools/devtools
MIT License
134 stars 33 forks source link

Unable to import jotai-devtools within an expo + react native app #50

Closed arjunvegda closed 1 year ago

arjunvegda commented 1 year ago

Discussed in https://github.com/jotaijs/jotai-devtools/discussions/41

Unable to import hooks from jotai-devtools/utils in an expo + react native app.

This should work

import { useAtomsDevtools } from 'jotai-devtools/utils';

export const AtomsDevtools = () => {
  useAtomsDevtools('store-name-here');
  return null;
};

See discussions/41#discussioncomment-5393898

Originally posted by **madsbuch** March 12, 2023 We just had to stop using `jotai-devtools` as it includes a dependency on the https://mantine.dev/ framework. Generally, it would be nice if packages like this one were headless and do not expect a document or to be run in a browser. Anyways, nice work and thanks for the time we got to have together!
arjunvegda commented 1 year ago

Root cause: Metro — expo's bundler is unable to resolve the multi-entry node module paths using exports field correctly (most probably due to jotai-devtools's ./dist?).

Ideally this should be fixed by turning on the unstable_enablePackageExports option but I couldn't make it work using config.resolver.unstable_enablePackageExports = true so I'd suggest filing an issue with Metro and getting their recommendation as well.

Here are a few fixes I could think of.

Fix 1 (recommended)

Expo users would resolve the path (jotai-devtools/utils) manually by configuring metro.config.js. Retains type safety for jotai-devtools/utils.

// metro.config.js
const path = require('path');
const { getDefaultConfig } = require('expo/metro-config');

const config = getDefaultConfig(__dirname);
config.resolver.resolveRequest = (context, moduleName, platform) => {
    if (moduleName === 'jotai-devtools/utils') {
        return {
            filePath: path.resolve(__dirname, 'node_modules/jotai-devtools/dist/utils.cjs.js'),
            type: 'sourceFile',
        };
    }

    return context.resolveRequest(context, moduleName, platform);
}
module.exports = config

Fix 2 (requires further investigation)

We add react-native field to jotai-devtools's package.json file to help metro resolve modules correctly. The caveat is that it only supports a string value.

Add this in jotai-devtools/package.json

"react-native": "./dist/utils.cjs.js"

Outstanding questions


I'm not a React-native expert by any means 😅 so it'd be great if someone could help me test if the hooks under jotai-devtools/utils work as expected 🙏

arjunvegda commented 1 year ago

Closing this as we have a good workaround for now. Happy to re-open if the issue persists.