skip to Main Content

React Native has a mechanism to automatically bundle and serve images corresponding to device’s screen density using @2x and @3x suffixes.

See: https://reactnative.dev/docs/images

The docs mention a require syntax, but I was wondering if this also works for import syntax? I can’t find any information on this and can’t find a way to test this.

// this automatically serves @1x, @2x, @3x
<Image source={require('./my-icon.png')} />

// this as well?
import icon from './my-icon.png';
<Image source={icon} />

2

Answers


  1. Chosen as BEST ANSWER

    I tested it by using different images for the @2x and @3x variants and they work exactly the same!

    enter image description here


  2. Take a look at the implementation of how React Native resolves assets: https://github.com/facebook/react-native/blob/main/Libraries/Image/AssetSourceResolver.js#L38

    Whenever you’re passing the source prop to an <Image /> component it will just lookup the import path on the filesystem and use that to resolve other density images. Since a path can be determined from both a CommonJS (require(…)) import and an ES Module import statement they will act the same for React Native’s asset resolution.

    If you really wanted to verify you could use a tool like Flipper, Proxyman or mitmproxy to inspect Metro’s network traffic and verify that your @2x or @3x device is resolving to something like http://localhost:8081/assets/[email protected]

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search