当在
Next中使用
styled-components
和 React 时,确保样式化的组件正确呈现可能变得具有挑战性。为了解决这个问题,Next 提供了compiler.styledComponents
标志
在next.config.js
如下:
compiler: {
styledComponents: true
}
但是,当启用此标志时,它会导致类名变得不可读,因为它们的大小呈指数增长。
下图说明
compiler.styledComponents
禁用和启用时类名的区别。
当
compiler.styledComponents
未设置时:
当
compiler.styledComponents
设置时:
有没有办法将班级名称的大小缩小到它们的常规
sc-XXXXXX
名称?
我应该注意到我们not使用最新版本的Next,而是
[email protected]
displayName
中禁用
babel-plugin-styled-components
感谢@vlad-vladov 为此指出文档。
在 Next.js 编译器的Next.js 12 和 13 文档中,声明 Next.js 使用
babel-plugin-styled-components
的端口并且 displayName
选项在开发中默认启用,在开发中禁用生产。 babel-plugin-styled-components
的文档说明了有关 displayName
选项的以下内容:
此选项通过更丰富的输出增强了每个组件上附加的 CSS 类名称,以帮助在没有 React DevTools 的情况下识别 DOM 中的组件。在您的页面源代码中,您会看到:
而不仅仅是<button class="Button-asdf123 asdf123" />
.<button class="asdf123" />
要禁用
displayName
,只需输入false
:
module.exports = {
compiler: {
styledComponents: { displayName: false }
}
}
为了进一步解释为什么你的类名这么长,
fileName
选项(默认启用)在启用时将当前文件的名称添加到 displayName
的开头。