'react-native-svg-transformer not working with the metro.config.js file

I am currently trying to use React Native SVG to render SVG components in my RN app. However, the metro.config.js configuration causes some errors I cannot seem to resolve.

I have installed react-native-svg and react-native-svg-transformer and combined the metro config file as such:

const { getDefaultConfig } = require("metro-config");

module.exports = (async () => {
  const {
    resolver: { sourceExts, assetExts }
  } = await getDefaultConfig();
  return {
    transformer: {
      getTransformOptions: async () => ({
        transform: {
          experimentalImportSupport: false,
          inlineRequires: false
        }
      }),
      babelTransformerPath: require.resolve("react-native-svg-transformer")
    },
    resolver: {
      assetExts: assetExts.filter(ext => ext !== "svg"),
      sourceExts: [...sourceExts, "svg"]
    }
  };
})();

However, I always get the following error:

[Sun Feb 13 2022 17:49:52.470]  ERROR    ReferenceError: Can't find variable: config
[Sun Feb 13 2022 17:49:52.472]  ERROR    Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication)
[Sun Feb 13 2022 17:49:52.473]  ERROR    Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication)

I tried restarting with npm start -- --reset-cache and after playing around with the config file, I noticed that it was the async that was causing the issue. The variable couldn't be found since the parent function isn't awaiting. I can't get around this when using getDefaultConfig(). How can I get around this?



Solution 1:[1]

This works for me:

const { assetExts, sourceExts } = require('metro-config/src/defaults/defaults');
const blacklist = require('metro-config/src/defaults/blacklist');
const { getDefaultConfig, mergeConfig } = require("metro-config");

const cfg = async () => await getDefaultConfig();

module.exports = mergeConfig(cfg, {
    transformer: {
        getTransformOptions: async () => ({
            transform: {
                experimentalImportSupport: false,
                inlineRequires: false
            }
        }),
        babelTransformerPath: require.resolve("react-native-svg-transformer")
    },
    resolver: {
        assetExts: assetExts.filter(ext => ext !== "svg"),
        sourceExts: [...sourceExts, "svg"],
        blacklistRE: blacklist([/ios\/build\/.*/])
    }
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1