打包为节点模块的TypeScript React组件中未呈现SVG图标

时间:2019-07-11 07:32:47

标签: node.js reactjs typescript svg webpack

我编写了一个节点模块,其中包含要包含在其他几个项目中的Typescript React组件。组件项目基于create-react-app。该组件包括一些SVG,这些SVG使用import { ReactComponent as Icon } from 'path/to/my/component.svg';语法explained in the documentation呈现为组件。该组件在测试页面中作为模块项目的一部分进行呈现,其中SVG图标可以很好地呈现。

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

我的调查结果

  • 我很肯定分布式分发包包含所有图标,并且相对路径正确
  • 使用tsc将组件编译为JS。将带有JS代码的分发文件夹复制到另一个项目中并从那里导入组件时,图标呈现正常状态
  • 使用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"
  }
}

模块项目的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.*"]
}

还包括.svg文件的类型定义,定义如下:

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

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

    const src: string;
    export default src;
}

SVG如何包含在我的组件中

组件包装器

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

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

使用图标

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

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

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

0 个答案:

没有答案
相关问题