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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With