首页 > 解决方案 > 如何将 SVG 从 typescript 自定义包导出到 React Native Project

问题描述

我有一个名为“app-packages”的自定义包,我希望我的所有 .png 和 .svg 都存储在这个包中。我设法导出 .png 文件,但在导出和使用 .svg 文件时遇到问题。

我已经在我的应用程序包中安装了 https://github.com/kristerkari/react-native-svg-transformerhttps://github.com/react-native-svg/react-native-svg并反应原生应用程序。

我试过的:

我在包中有 src/Arrow.svg,我在 src/index.tsx 中像这样导出它。

export { default as SvgPicture} from './Arrow.svg'

我已经在 src/ 中创建了一个 declaration.d.ts

declare module "*.svg" {
    import React from 'react';
    import {
        SvgProps
    } from "react-native-svg";
    const content: React.FC<SvgProps> ;
    export default content;
}

这是我的 tsconfig.json

{
"compilerOptions": {
  "target": "ESNext",
  "module": "ESNext",
  "strict": true,
  "outDir": "build",
  "declaration": true,
  "jsx": "react",
  "importHelpers": true,
  "moduleResolution": "node",
  "experimentalDecorators": true,
  "esModuleInterop": true,
  "allowSyntheticDefaultImports": true,
  "noImplicitAny": false,
  "allowJs": false,
  "sourceMap": true,
  "lib": ["es6", "dom", "dom.iterable", "es2016", "es2017"],
  "forceConsistentCasingInFileNames": true,
  "resolveJsonModule": true,
  "isolatedModules": true,
  "noImplicitReturns": true,
  "noImplicitThis": true,
  "strictNullChecks": true,
  "suppressImplicitAnyIndexErrors": true,
  "noUnusedLocals": true,
  "noUnusedParameters": true,
  "noEmit": true
},
"include": ["src", "src/declaration.d.ts"],
"exclude": ["node_modules", "build"]

}

完成所有这些之后,我构建了包并在我的应用程序中进行了尝试。像这样

import {SvgPicture} from 'app-packages';

并在渲染中这样称呼它,因为我已经安装了 react-native-svg-transformer

 <SvgPicture />

但结果是这样的

Invariant Violation: View config getter callback for component `../../../Arrow.svg` must be a function (received `undefined`).

如果 SVG 文件在我的 react native 应用程序中,上面的步骤将显示 .svg。但是如果我将它移到应用程序包中它会失败。有人有解决方案吗?

标签: typescriptreact-nativesvgpackageexport

解决方案


推荐阅读