kristerkari / react-native-svg-transformer

Import SVG files in your React Native project the same way that you would in a Web application.
MIT License
1.57k stars 116 forks source link

babel plugin not loaded causing crash with react-native-reanimated v2 #113

Open Bushuo opened 3 years ago

Bushuo commented 3 years ago

Description

I use react-native-reanimated@2.0.0-rc.0 which requires me to use a plugin for babel. Important to say is my project is a monorepo with yarn workspaces.

// babel.config.js
module.exports = {
  presets: ['module:metro-react-native-babel-preset'],
  plugins: ['react-native-reanimated/plugin'],
};

If I use

// metro.config.js
...
babelTransformerPath: require.resolve('react-native-svg-transformer')
...

the app crashes silently. Only logcat outputs a seemingly unrelated error caused by the plugin not being loaded.

I fixed this by creating

// customTransformer.js
var svgTransformer = require('react-native-svg-transformer');
var upstreamTransformer = require('metro-babel-transformer');

module.exports.transform = function ({src, filename, options}) {
  if (filename.endsWith('.svg')) {
    return svgTransformer.transform({src, filename, options});
  } else {
    return upstreamTransformer.transform({src, filename, options});
  }
};

This loads metro-babel-transformer instead of metro-react-native-babel-transformer. The later is loaded by react-native-svg-transformer on RN >= 0.59

I don't know the implications of loading metro-babel-transformer but it's the default string for babelTransformerPath so it seems right.

Should I make a PR for this change?

Here is a link to the somewhat MVE repo where I could reproduce the crash https://github.com/Bushuo/reanimated2-monorepo-crash Quite large because I needed to experiment a little bit to find the cause of the crash...

Dependencies

"react-native": "0.63.4",
"react-native-reanimated": "2.0.0-rc.0",
"react-native-svg": "12.1.0",
"react-native-svg-transformer": "0.14.3",
kristerkari commented 3 years ago

This loads metro-babel-transformer instead of metro-react-native-babel-transformer.

Hmm.. do you know what's the difference between these two?

Bushuo commented 3 years ago

Sorry no. I just know that metro-babel-transformer is the default string when console.logging babelTransformerPath

alfalcon90 commented 3 years ago

Thanks, @Bushuo. Adding customTransformer.js to the root folder and replacing this line in metro.config.js fixed it for me:

-  babelTransformerPath: require.resolve('react-native-svg-transformer'),
+  babelTransformerPath: require.resolve('./customTransformer.js'),