uloco
uloco

Reputation: 2421

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?

Upvotes: 3

Views: 1948

Answers (1)

Petr Bela
Petr Bela

Reputation: 8741

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.

Upvotes: 3

Related Questions