facebook / metro

🚇 The JavaScript bundler for React Native
https://metrobundler.dev
MIT License
5.16k stars 613 forks source link

[discussion] supporting platform-specific Babel plugins #47

Open ide opened 7 years ago

ide commented 7 years ago

Do you want to request a feature or report a bug? Feature

What is the current behavior? Currently Metro doesn't tell Babel the platform for which it's transforming a file.

What is the desired behavior? We'd like to transform files differently based on the platform (ex: Android, iOS, Windows). These are a couple of use cases:

  1. The JS VM on a platform may support more features of modern JS, like classes. A platform-specific Babel plugin would omit the ES class transform on one platform but not another.

  2. RN Windows needs to override some of the require() calls. Specifically, it wants to rewrite require('Text') (inside of react-native) to require('react-native-windows/Libraries/Text/Text.windows.js'). Currently RN Windows relies on a private implementation detail of Haste to override how Metro resolves modules. With platform-specific Babel plugins, RN Windows could offer a Babel plugin that rewrites requires only if platform=windows were specified. (The motivation for this is: this would help remove one of the last reasons why RN OSS needs Haste.)

There are a few different ways we could achieve this:

  1. Set an environment variable (in the transform worker) that Babel plugins can inspect: METRO_PLATFORM.
  2. Somehow passing the platform into the Babel plugins another way (via options? not sure if this can be done cleanly)
  3. Platform-specific presets: the default transformer.js inside Metro already knows how to look up .babelrc. We could modify this code to look up .{android,ios,windows,native,web}.babelrc. This feels easy to explain to someone who knows about platform-specific modules like module.ios.js.
  4. Something else?

Regardless of the option, we'd need to make sure to include the platform in the transform cache key. I think this already happens but don't quote me on that =)

Please provide your exact metro-bundler configuration and mention your metro-bundler, node, yarn/npm version and operating system. Metro 0.11

cpojer commented 6 years ago

Do you wanna work on a PR for this? :)

ide commented 6 years ago

Yeah. Before that what I'm looking for from the Metro team is input on (a) what is actually useful for professionals and (b) what would be easy to maintain.

simonbuchan commented 6 years ago

Babel 7 will have .babelrc.js which can do whatever, e.g. process.env.REACT_NATIVE_PLATFORM === 'windows'.

Akronae commented 1 year ago

6 years later and still no way to check which platform is being built from a Babel plugin using Metro ? (with Expo)