require() Image doesn't work but import does
ktprograms opened this issue · 8 comments
Describe the bug
Using import logo from './logo.png';
in the example code after running npx create-react-native-web-app ReactNativeWebAppExample
works on all three platforms to show the image. But if I comment that line out and replace it with const logo = require('./logo.png');
, then the image shows on Android and iOS, but on web it shows nothing.
To Reproduce
My Code: https://github.com/ktprograms/ReactNativeWebAppExample
Steps to reproduce the behavior:
git clone https://github.com/ktprograms/ReactNativeWebAppExample
cd ReactNativeWebAppExample
yarn
cd ios && pod update && pod install && cd -
yarn ios (runs on iOS)
yarn android (runs on Android)
yarn web (runs on Web)
Expected behavior
require()
-ing an image should work on Web too?
Screenshots
(iOS, same on Android):
(Web):
Desktop (please complete the following information):
- OS: I'm using MacOS 11.2.3 on a MacBook Air (M1, 2020). The above steps to reproduce were run in a Terminal.app window with Rosetta enabled.
- Browser: Safari
- Version 14.0.3 (16610.4.3.1.7)
Smartphone (please complete the following information):
- Device: iPhone 11 simulator
- OS: iOS 14.5
- Device: Android Emulator (Pixel_3a_API_S)
- OS: Android Version S
@ktprograms not sure why that doesn't work, might be related to webpack.
In the react native web docs they don't use require
https://necolas.github.io/react-native-web/docs/image/
I noticed the docs don't use require()
too, but @react-navigation/stack
uses it for the back button in the header. I don't really understand webpack and there doesn't seem to be any webpack config in the blank created project. Is it hidden by create-react-app
or something?
yes well.. import should work just as well, no?
It does for my own code, but the back button doesn't show up because react-navigation uses require in its code. See react-navigation/react-navigation#9647 (my issue)
well it seems like they have a few issues in create-react-app around images not showing https://github.com/facebook/create-react-app/issues?q=is%3Aissue+is%3Aopen+require+images
Thanks, I didn't think to look in create-react-app. Using require('source/to/image.png').default
(seen here) worked. Unfortunately, react-navigation doesn't have the .default
at the end (source here).
Thanks for the help! I've used patch-package
to fix it for now, and I've opened an issue in react-navigation
alerting them about it.