React Storybook SVG Failed to execute 'createElement' on 'Document'

后端 未结 3 1986
抹茶落季
抹茶落季 2021-01-12 02:05

I\'m trying to add Storybook to an existing React app but getting errors with imported svg files. The svg is imported and used like:

import Border from \'./i         


        
3条回答
  •  花落未央
    2021-01-12 02:30

    This is happening because Storybook's default webpack config has its own svg config:

    { 
      test: /\.(svg|ico|jpg|jpeg|png|gif|eot|otf|webp|ttf|woff|woff2|cur|ani)(\?.*)?$/,
      loader: 'file-loader',
      query: { name: 'static/media/[name].[hash:8].[ext]' }
    },
    

    I'm pretty sure this is the cause, because you can see the path outlined in error message: query: { name: 'static/media/[name].[hash:8].[ext]' } -> static/media/border.inline.258eb86a.svg

    The solution can be to find the existing loader & change / or add an exclude rule to it. Here's an example of a custom .storybook/webpack.config.js:

    // storybook 4
    module.exports = (_, _, config) => {
    // storybook 5
    module.exports = ({ config }) => {
      const rules = config.module.rules;
    
      // modify storybook's file-loader rule to avoid conflicts with your inline svg
      const fileLoaderRule = rules.find(rule => rule.test.test('.svg'));
      fileLoaderRule.exclude = /\.inline.svg$/;
    
      rules.push({
        test: /\.inline.svg$/,
        ...
        }],
      });
    
      return config;
    };
    

提交回复
热议问题