admin管理员组

文章数量:1404577

I'm trying to fetch SVG images dynamically in my react ponent, but so far I'm getting this error Uncaught (in promise) TypeError: Failed to fetch dynamically imported module. This is my code sample

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>
  );
};

I'm trying to fetch SVG images dynamically in my react ponent, but so far I'm getting this error Uncaught (in promise) TypeError: Failed to fetch dynamically imported module. This is my code sample

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>
  );
};

This code works perfectly in the storybook, but when I use it in the react ponent it won't load images and that error pops. What am I doing wrong?

Share Improve this question asked Apr 28, 2020 at 19:41 MilosMilos 6193 gold badges10 silver badges24 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 2

This issue is solved with setting some rules in webpack.config. It was issue with .svg. This is the rule that solved the issue:

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

本文标签: javascriptUncaught (in promise) TypeError Failed to fetch dynamically imported moduleStack Overflow