SVG 图标未在绑定为节点模块的 TypeScript React 组件中呈现

dok*_*der 5 svg node.js typescript reactjs webpack

我编写了一个节点模块,其中包含一个我想包含在其他几个项目中的 Typescript React 组件。组件项目基于 create-react-app。该组件包括一些使用文档中解释import { ReactComponent as Icon } from 'path/to/my/component.svg';语法呈现为组件的 SVG 。该组件作为模块项目的一部分在测试页面中呈现,其中 SVG 图标呈现良好。

但是,当我捆绑模块并将其包含在另一个项目中时,组件会呈现,但没有所有图标。控制台告诉我现在导入的所有图标组件都是undefined. 我想问题可能出在 webpack 上,但不知道如何解决。另外,由于与问题无关的原因,我宁愿不弹出 create-react-app 项目。

我的调查结果

  • 我确信分布式包包含所有图标并且相对路径是正确的
  • 组件使用 tsc 编译成 JS。将带有 JS 代码的 distrubution 文件夹复制到另一个项目并从那里导入组件时,图标呈现正常
  • yarn pack用于创建一个包并在另一个项目中作为依赖安装时,图标消失了

健康)状况

  • 我宁愿不必弹出组件项目来编辑 webpack.config

模块项目的 package.json

{
  "name": "MyFancyComponent",
  "version": "1.0.1",
  "main": "dist/index.js",
  "license": "UNLICENSED",
  "dependencies": {
    "axios": "^0.19.0",
    "husky": "^2.4.1",
    "i18next": "^17.0.4",
    "node-sass": "^4.12.0",
    "test-name": "./test-name-v1.0.0.tgz",
    "test-name2": "./test-name2-v1.0.1.tgz",
    "typescript": "3.5.2"
  },
  "devDependencies": {
    "@types/i18next": "^12.1.0",
    "@types/jest": "24.0.15",
    "@types/node": "12.0.8",
    "@types/react": "^16.8.22",
    "@types/react-dom": "16.8.4",
    "@types/react-i18next": "^8.1.0",
    "react": "^16.8.6",
    "react-dom": "^16.8.6"
  },
  "peerDependencies": {
    "react": "^16.8.6",
    "react-dom": "^16.8.6"
  },
  "files": [
    "/dist",
    "/style",
    "index.d.ts"
  ],
  "scripts": {
    "start": "react-scripts start",
    "dist": "tsc && cp -r src/lib/style/* dist/style && cp -r src/lib/tenants/* dist/tenants"
  }
}

Run Code Online (Sandbox Code Playgroud)

模块项目的tsconfig

{
  "compilerOptions": {
    "allowJs": false,
    "declaration": true,
    "noEmit": false,
    "noImplicitAny": true,
    "noImplicitThis": true,
    "outDir": "./dist",
    "rootDir": "./src/lib",
    "suppressImplicitAnyIndexErrors": true,
    "removeComments": true,
    "types": ["node"],
    "jsx": "react",
    "typeRoots": ["./src/@types", "./node_modules/@types"]
  },
  "include": ["src/@types", "src/lib"],
  "exclude": ["src/**/*.test.*"]
}
Run Code Online (Sandbox Code Playgroud)

.svg 文件的类型定义也包括在内,定义如下:

declare module '*.svg' {
    import * as React from 'react';

    export const ReactComponent: React.FunctionComponent<React.SVGProps<SVGSVGElement>>;

    const src: string;
    export default src;
}
Run Code Online (Sandbox Code Playgroud)

我的组件中如何包含 SVG

组件包装器

import React from 'react';
import { ReactComponent as Icon } from 'pat/to/component.svg';

export default (props: any) => (
    <i>
        <Icon />
    </i>
);

Run Code Online (Sandbox Code Playgroud)

使用图标

import React from 'react';
import IconComponent from './icons/icon-component';

const MyComponent: React.FunctionComponent<{}> = () => (
    <div>
         <IconComponent />
    </div>
);

Run Code Online (Sandbox Code Playgroud)

关于如何解决这个问题的任何想法?