我正在尝试将 Storybook 添加到现有的 React 应用程序,但导入的 svg 文件出现错误。 svg 的导入和使用如下:
import Border from './images/border.inline.svg'
...
<Border className="card__border" />
这在应用程序运行和构建时有效,但我在 Storybook 中收到错误。怎么会这样?
Failed to execute 'createElement' on 'Document': The tag name provided ('static/media/border.inline.258eb86a.svg') is not a valid name.
Error: Failed to execute 'createElement' on 'Document': The tag name provided ('static/media/border.inline.258eb86a.svg') is not a valid name.
默认的 webpack.config.js 有:
...
{
test: /\.inline.svg$/,
loader: 'svg-react-loader'
},
...
此外,现有代码使用 webpack 3,而我使用的是 Storybook V4。
请您参考如下方法:
发生这种情况是因为 Storybook 的 default webpack config有自己的 svg 配置:
{
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]' }
},
我很确定这就是原因,因为您可以看到错误消息中概述的路径: query: { name: 'static/media/[name].[hash:8].[ext] ' } -> static/media/border.inline.258eb86a.svg
解决方案可以是找到现有的加载程序并更改/或向其添加排除规则。以下是自定义 .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;
};






