Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native image import with import() instead of require()

Is there a way of importing an asset in React-Native dynamically with import(...) instead of require(...)?

We are using @typescript-eslint/recommended and I'd like to keep the rule @typescript-eslint/no-var-requires enabled, which is marking this as an error.

The way we do it now:

const foo = require("../path/to/foo.png")

How I want to do it:

const foo = import("../path/to/foo.png")

It would also be ok if I could just use normal ESM import syntax rather than require. Is there any way?

like image 693
uloco Avatar asked Apr 15 '26 06:04

uloco


1 Answers

React Native's Metro bundler doesn't support dynamic imports https://github.com/facebook/metro/issues/52, so what you're asking is not possible. (Btw there are now inline requires which you can use e.g. for https://reactnative.dev/docs/ram-bundles-inline-requires but that's a different thing).

On a separate note, in your example const foo = require('.../foo.png') is actually a static require; the equivalent using ES6 modules would be import foo from '.../foo.png'. That might actually work, although I think it's better to use <Image source={require('..')} /> directly rather than introduce another variable.

like image 194
Petr Bela Avatar answered Apr 18 '26 14:04

Petr Bela