How to show SVG file on React Native?

后端 未结 13 1577
被撕碎了的回忆
被撕碎了的回忆 2020-12-12 11:13

I want to show svg files (I have bunch of svg images) but the thing I couldn\'t find the way to show. I tried to use Image and Use componen

13条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-12 11:59

    Use https://github.com/kristerkari/react-native-svg-transformer

    In this package it is mentioned that .svg files are not supported in React Native v0.57 and lower so use .svgx extension for svg files.

    For web or react-native-web use https://www.npmjs.com/package/@svgr/webpack


    To render svg files using react-native-svg-uri with react-native version 0.57 and lower, you need to add following files to your root project

    Note: change extension svg to svgx

    step 1: add file transformer.js to project's root

    // file: transformer.js
    
    const cleanupSvg = require('./cleanup-svg');
    
    const upstreamTransformer = require("metro/src/transformer");
    
    // const typescriptTransformer = require("react-native-typescript-transformer");
    // const typescriptExtensions = ["ts", "tsx"];
    
    const svgExtensions = ["svgx"]
    
    // function cleanUpSvg(text) {
    //   text = text.replace(/width="([#0-9]+)px"/gi, "");
    //    text = text.replace(/height="([#0-9]+)px"/gi, "");
    //    return text;
    // }
    
    function fixRenderingBugs(content) {
      // content = cleanUpSvg(content); // cleanupSvg removes width and height attributes from svg
      return "module.exports = `" + content + "`";
    }
    
    
    module.exports.transform = function ({ src, filename, options }) {
      // if (typescriptExtensions.some(ext => filename.endsWith("." + ext))) {
      //  return typescriptTransformer.transform({ src, filename, options })
      // }
    
      if (svgExtensions.some(ext => filename.endsWith("." + ext))) {
        return upstreamTransformer.transform({
          src: fixRenderingBugs(src),
          filename,
          options
        })
      }
    
      return upstreamTransformer.transform({ src, filename, options });
    }
    
    

    step 2: add rn-cli.config.js to project's root

    module.exports = {
        getTransformModulePath() {
          return require.resolve("./transformer");
        },
        getSourceExts() {
          return [/* "ts", "tsx", */ "svgx"];
        }
      };
    

    The above mentioned solutions will work in production apps too ✅

提交回复
热议问题