【问题标题】:Uncaught (in promise) TypeError: Failed to fetch dynamically imported module未捕获(承诺中)TypeError:无法获取动态导入的模块
【发布时间】:2020-08-12 18:19:15
【问题描述】:

我正在尝试在我的 react 组件中动态获取 SVG 图像,但到目前为止,我收到此错误 Uncaught (in promise) TypeError: Failed to fetch dynamic imports module。这是我的代码示例

import React from 'react';
import { CustomSvgIcon } from '../../util/CustomSvgIcon';


const Icon = ({ iconName }: IconProps) => {
  const [menuIcon, setIcon] = React.useState<string | null>(null);

  React.useEffect(() => {
    if (iconName) {
      import(`../../../assets/svg/${iconName}.svg`)
        .then((bla) => setIcon(bla.default))
        .catch((error) => console.log(error));
    }
  }, []);
  return (
    <CustomSvgIcon>
      {menuIcon ? menuIcon : null}
    </CustomSvgIcon>
  );
};

此代码在故事书中完美运行,但是当我在反应组件中使用它时,它不会加载图像并且会弹出错误。我做错了什么?

【问题讨论】:

    标签: javascript reactjs typescript webpack


    【解决方案1】:

    这个问题可以通过在 webpack.config 中设置一些规则来解决。这是.svg 的问题。这是解决问题的规则:

    {
          test: /\.svg$/,
          use: [
            {
              loader: '@svgr/webpack',
              options: {
                icon: true,
              },
            },
          ],
        }
    

    【讨论】:

      猜你喜欢
      • 2020-06-14
      • 1970-01-01
      • 1970-01-01
      • 2018-04-18
      • 1970-01-01
      • 2019-05-16
      • 2018-05-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多