Describe the bug
When I import SVGs into storybook, the imports are undefined.
To Reproduce
import React from 'react'
import { storiesOf } from '@storybook/react'
import { ReactComponent as Example } from './example.svg'
console.log(Example) // undefined
Expected behavior
The SVG should be imported successfully.
Code snippets
If applicable, add code samples to help explain your problem.
System:
"@storybook/react": "^4.1.11"
Additional context
Judging by this issue, this should be supported out of the box without a custom Webpack or Babel config.
Works fine for me, but I used create-react-app which adds "react-scripts": "2.1.3",
(at least for me running 5.0). Check that that's in your dependencies as >2.0 per this
The slow start guide doesn't mention anything about the scripts version in case you're adding to an old react project, it might be worth adding adding as a dependency or perhaps just to the guide, idk.
Confirmed, this should only be supported out of the box for CRA apps. We plan to update the defaults post 5.0 release.
Not using create-react-app explicitly. Managed to get this working with custom webpack config and manually installing @svgr/webpack
.
Glad to hear it. We'll try to make that a lot easier sometime soon.
Been struggling getting this to work with Gatsby, TS, Storybook 5 setup. Works fine in Gatsby, but not in Storybook unfortunately 馃槩
For those interested, I was able to get .svg
imports working using the following custom webpack config
module.exports = ({ config, mode }) => {
config.module.rules = config.module.rules.map(rule => {
if (!rule.test.test(".svg")) {
return rule;
}
const newRule = rule;
// Changes existing default rule to not handle SVG files
newRule.test = /\.(ico|jpg|jpeg|png|gif|eot|otf|webp|ttf|woff|woff2)(\?.*)?$/;
return newRule;
});
// Adds new SVG loader
config.module.rules.push({
test: /\.svg$/,
use: ["@svgr/webpack", "url-loader"]
});
return config;
};
for reference: https://storybook.js.org/docs/configurations/custom-webpack-config/
hey @pedrombafonso, thank you for the solution.
but let's try to make it more adaptable:
module.exports = ({ config, mode }) => {
const assetRule = config.module.rules.find(({ test }) => test.test('.svg'));
const assetLoader = {
loader: assetRule.loader,
options: assetRule.options || assetRule.query,
};
config.module.rules.unshift({
test: /\.svg$/,
use: ['@svgr/webpack', assetLoader],
});
config.module.rules = [{ oneOf: config.module.rules }];
return config;
}
Most helpful comment
For those interested, I was able to get
.svg
imports working using the following custom webpack configfor reference: https://storybook.js.org/docs/configurations/custom-webpack-config/