Mar*_*son 14 reactjs webpack storybook
我正在尝试将 Storybook 添加到现有的 React 应用程序中,但在导入的 svg 文件中出现错误。svg 被导入并使用如下:
import Border from './images/border.inline.svg'
...
<Border className="card__border" />
Run Code Online (Sandbox Code Playgroud)
这在应用程序运行和构建时有效,但在 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.
Run Code Online (Sandbox Code Playgroud)
默认的 webpack.config.js 有:
...
{
test: /\.inline.svg$/,
loader: 'svg-react-loader'
},
...
Run Code Online (Sandbox Code Playgroud)
此外,现有代码使用 webpack 3,而我使用的是 Storybook V4。
Der*_*yen 11
这是因为 Storybook 的默认 webpack 配置有自己的 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]' }
},
Run Code Online (Sandbox Code Playgroud)
我很确定这就是原因,因为您可以看到错误消息中列出的路径: 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;
};
Run Code Online (Sandbox Code Playgroud)
小智 6
在 Storybook 6 中,您必须像这样导入它:
import { ReactComponent as Border } from './images/border.inline.svg'
Run Code Online (Sandbox Code Playgroud)
如果它也适用于您的版本,请尝试一下,因为这个问题是一年前的。
小智 5
看来 Storybook V6 他们已经更改了默认的 webpack 配置。我发现上述答案对我不起作用。
他们不再有 SVG 规则,因此对 SVG 的测试要么出错,要么返回 undefined。
有一个oneOf
规则,module.rules
它包含一个没有测试的加载器作为最后一条规则:
{
loader: '/Users/alexwiley/Work/OneUp/resources/client/node_modules/react-scripts/node_modules/file-loader/dist/cjs.js',
exclude: [Array],
options: [Object]
}
Run Code Online (Sandbox Code Playgroud)
这是罪魁祸首,您需要确保文件加载不包括所有内联 SVG 文件,否则会出错。
将以下内容添加到您的.storybook/main.js
文件中:
webpackFinal: async(config, { configType }) => {
config.module.rules.forEach((rule) => {
if (rule.oneOf) {
// Iterate over the oneOf array and look for the file loader
rule.oneOf.forEach((oneOfRule) => {
if (oneOfRule.loader && oneOfRule.loader.test('file-loader')) {
// Exclude the inline SVGs from the file loader
oneOfRule.exclude.push(/\.inline\.svg$/);
}
})
// Push your SVG loader onto the end of the oneOf array
rule.oneOf.push({
test: /\.inline\.svg$/,
exclude: /node_modules/,
loader: 'svg-react-loader', // use whatever SVG loader you need
})
}
});
return config;
Run Code Online (Sandbox Code Playgroud)
}
归档时间: |
|
查看次数: |
11965 次 |
最近记录: |