react-native-svg-transformer无法处理metro.config.js文件

blmhpbnm  于 2023-06-24  发布在  React
关注(0)|答案(2)|浏览(140)

我目前正在尝试使用React Native SVG在我的RN应用程序中渲染SVG组件。然而,metro.config.js配置导致了一些我似乎无法解决的错误。
我安装了react-native-svg和react-native-svg-transformer,并将metro配置文件组合成这样:

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"]
    }
  };
})();

但是,我总是得到以下错误:

[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)

我试着用npm start -- --reset-cache重新启动,在玩了配置文件之后,我注意到是异步导致了这个问题。找不到变量,因为父函数没有等待。我无法在使用getDefaultConfig()时解决这个问题。我该怎么办?

wwodge7n

wwodge7n1#

这对我很有效:

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\/.*/])
    }
});
fdx2calv

fdx2calv2#

只需将inlineRequires设置为true
完整的设置应该看下一个:

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

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

相关问题