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

后端 未结 3 1967
抹茶落季
抹茶落季 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:17

    I got it working with

    ...
    module.exports = {
      module: {
        rules: [
          {
            test: /\.inline.svg$/,
            loader: 'svg-react-loader'
          }
        ]
      }
    }
    
    0 讨论(0)
  • 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;
    };
    
    0 讨论(0)
  • 2021-01-12 02:32

    In Storybook 6, You have to import it like this:

    import { ReactComponent as Border } from './images/border.inline.svg'
    

    Try that if it also works for your version since this question is from a year ago.

    0 讨论(0)
提交回复
热议问题