necolas / react-native-web

Cross-platform React UI packages
https://necolas.github.io/react-native-web
MIT License
21.68k stars 1.79k forks source link

Make asset registry globally available #2720

Closed nandorojo closed 1 month ago

nandorojo commented 1 month ago

What

Exposes the asset registry array as a global variable so that libraries can access the assets without needing to install react-native-web.

Why

I build many open source libraries for React Native & React Native Web, many of which render an image under the hood.

In particular, I often want to do this in my libraries:

<img src={require('./local-image.png')} />

However, for libraries using Metro for Web, this doesn't work because ther result of require is a number.

I'd love to be able to do this:

function MyLibrarysComponent({ src }) {
  const asset = typeof src === 'number' ? globalThis.__react_native_web_assets[src] : src
}

I am explicitly not interested in importing Image from react-native-web, because I want to support web-only apps without adding requiring additional dependencies or configuration.

Workaround

The only way to fix this currently would be to import resolveAssetSource from react-native-web's internals. However, this would require adding react-native-web as a dependency of the library, just to support Metro Web users.

With this PR, I can confidently pull from the global variable for users which certainly have react-native-web installed, without requiring Next.js/Vite/Remix users to install it.

codesandbox-ci[bot] commented 1 month ago

This pull request is automatically built and testable in CodeSandbox.

To see build info of the built libraries, click here or the icon next to each commit SHA.

Latest deployment of this branch, based on commit cf6ed6cfee200bdf2ba14b93c28fece326e549e2:

Sandbox Source
react-native-web-examples Configuration
necolas commented 1 month ago

Hi, I don't think this makes sense for RNfWeb. Inline requires are a React Native pattern, that otherwise should be supported by bundlers, especially if your use case doesn't involve depending on RNfWeb. Thanks

nandorojo commented 1 month ago

Yeah I think we’re going to upstream this in expo’s metro config instead https://github.com/expo/expo/pull/31955