Exclude a specific package from react metro bundler when building

Viewed 436

I have a library that requires:

  • rnkata.js when running in react native
  • webkata.js when running in a browser
  • nodekata.js when running in node

This hack works OK as long as I'm only targeting node/web:

if (getEnv() == "node") {
  eval('require')('nodekata')
} else {
  require('webkata')
}

But once I started targeting mobile, metro bundler would complain "webkata not available":

if (getEnv() == "node") {
  eval('require')('nodekata')
} else if (getEnv() == "mobile") {
  require('rnkata')
} else {
  require('webkata')
}

Obviously, I can't use the same eval hack - or I break either webpack or RN. Is there some documentation on how to manage this situation? IE: how can i suppress bundling or interpreting of a 'require' call by platform.

Is there a "suppress by module name" feature? Or some other way to have a platform-specific module?

1 Answers

Metro recently added support for Optional imports. It should be available in React Native v0.63.0. See this issue and this PR for more details.

You could also consider doing naming the files to show which platforms they support. For example:

index.js - web version
index.native.js - android & ios only version
index.android.js - android version
index.ios.js - ios version
Related