减少在Next中styled-component的className长度

6

在使用 styled-componentsReactNext 中时,确保样式组件正确呈现可能会变得具有挑战性。为了解决这个问题,Next 提供了以下代码中的 compiler.styledComponents 标志,位于 next.config.js 文件中:

compiler: {
    styledComponents: true
}

然而,当启用此标志时,随着类名的大小呈指数级增长,它们变得不可读。
以下图片演示了在禁用和启用compiler.styledComponents时类名之间的差异。
当未设置compiler.styledComponents时:

before

compiler.styledComponents 被设置时:

after

有没有办法将类名尺寸缩减为它们的正常sc-XXXXXX名称?

需要注意的是,我们使用的不是最新版本的Next,而是next@12.3.4


2
你尝试过在 next.config.js 中使用 displayName 和 fileName 选项吗?请参考 https://nextjs.org/docs/advanced-features/compiler#styled-components - Vlad Vladov
1个回答

5

在中禁用displayName

感谢@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的开头。


1
太好了-谢谢! 不过,我选择保持 displayName 属性启用,只禁用 fileName。 :-) - GROVER.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接