不能将 SVG 用作 NextJS 应用程序和 Storybook 的模块,使用绝对路径导入。通过许多尝试的设置,我能够在 Next 或 Storybook 中导入 SVG,但不能同时在两者中导入。我将此设置用于 babel-plugin-inline-react-svg
:
// .babelrc
{
...
"plugins": [
...
"inline-react-svg"
]
}
使用这个插件 Storybook 不需要任何配置,这个示例代码可以按预期工作:
import Wrapper from '../../../components/Wrapper';
import IconSVG from '../../../icons/sandwich.svg';
export const WrappedSVG = () => (
<Wrapper>
<IconSVG />
</Wrapper>
);
但以下不是:
import Wrapper from 'components/Wrapper';
import IconSVG from 'icons/sandwich.svg';
export const WrappedSVG = () => (
<Wrapper>
<IconSVG />
</Wrapper>
);
Wrapper 正在处理,但不是图标:找不到模块
这里是 svgr
设置:
// next.config.js
module.exports = {
webpack(config, options) {
...
config.module.rules.push({
test: /\.svg$/,
use: ['@svgr/webpack'],
});
return config;
},
};
// .storybook/main.js
module.exports = {
...
webpackFinal: async config => {
...
config.module.rules.unshift({
test: /\.svg$/,
use: ['@svgr/webpack'],
});
return config;
},
}
此配置在应用程序端运行良好,但在 Storybook 中我得到 DOMException: "String contains an invalid character"
我的 npm run dev
脚本是这样的:ts-node --project tsconfig.server.json src/server.ts
(通过 nodemon
)。
我希望有人能给我一个提示,如何让 SVG 组件的绝对导入同时适用于 NextJS 和 Storybook。
最佳答案
有an answer到另一个对我有用的问题。
这可能是因为与 Storybook 的默认 SVG 加载器发生冲突。这是对我有用的:
module.exports = {
webpackFinal: async (config, { configType }) => {
const rules = config.module.rules;
const fileLoaderRule = rules.find(rule => rule.test.test('.svg'));
fileLoaderRule.exclude = /\.svg$/;
rules.push({
test: /\.svg$/,
use: ["@svgr/webpack"],
});
return config;
}
};
关于typescript - NextJS、Storybook、SVG 和绝对导入路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60691412/