简体   繁体   English

为 nextjs 项目设置关键 css 并删除不需要的 CSS 的正确方法

[英]correct way to setup critical css for nextjs project and remove unwanted CSS

I have a NextJS project setup -> https://github.com/stefanre1/nextjs-setup我有一个 NextJS 项目设置-> https://github.com/stefanre1/nextjs-setup

I am wondering what's the right way to remove unwanted css from Tailwindcss and add critical css to each page.我想知道从 Tailwindcss 中删除不需要的 css 并将关键的 css 添加到每个页面的正确方法是什么。

I have tried following some blogs to achieve the same but was not successful.我曾尝试关注一些博客以达到同样的效果,但没有成功。

Obviously I have deleted what I have tried as it was not working.显然我已经删除了我尝试过的东西,因为它不起作用。 For now kept the bare minimum code in the repository.现在在存储库中保留最少的代码。

Any help or suggestions would be helpful.任何帮助或建议都会有所帮助。

I have tried solution from here to add to head, but it adds all CSS as expected.我已经尝试从这里添加到头部的解决方案,但它按预期添加了所有 CSS。 I have tried this one as well我也试过这个

You should try PurgeCSS .你应该试试PurgeCSS Coming directly from the docs:直接来自文档:

PurgeCSS analyzes your content and your css files. PurgeCSS 分析您的内容和您的 css 文件。 Then it matches the selectors used in your files with the one in your content files.然后它将文件中使用的选择器与内容文件中的选择器相匹配。 It removes unused selectors from your css, resulting in smaller css files它从您的 css 中删除未使用的选择器,从而生成更小的 css 文件

The Tailwind docs actually have a whole section on this issue here , detailing how to setup PurgeCSS and other methods to reduce file size. Tailwind 文档实际上在这里有一整节关于这个问题,详细介绍了如何设置 PurgeCSS 和其他方法来减小文件大小。 PurifyCSS is another alternative as well. PurifyCSS也是另一种选择。

Edit: I just realized you tried PurgeCSS already, perhaps you made a mistake in your configuration, and should try the setup directly from the docs.编辑:我刚刚意识到您已经尝试过 PurgeCSS,也许您在配置中犯了错误,应该直接从文档中尝试设置。

I have seen your code.我看过你的代码。

  • Remove @zeit/next-css and next-purgecss packages because Nextjs provides built-in support for css.删除 @zeit/next-css 和 next-purgecss 包,因为 Nextjs 提供了对 css 的内置支持。
  • postcss.config.js file will take care of everything. postcss.config.js 文件将处理所有事情。
  • If you want to put any CSS in safelist of purgeCSS, you can do that by adding in safelist array in postcss config file.如果您想将任何 CSS 放入 purgeCSS 的安全列表中,您可以通过在 postcss 配置文件中添加安全列表数组来实现。
  • Sometimes we want to ignore certain parts of a css file from purgeCSS.有时我们想忽略来自 purgeCSS 的 css 文件的某些部分。 In order to do so, add为此,请添加

 /*. purgecss start ignore */...your css properties /*! purgecss end ignore */

You can follow this tutorial to setup your postcss config您可以按照本教程设置您的 postcss 配置

purgecss ignore discussion purgecss 忽略讨论

Tell me if it works or you have some doubt.告诉我它是否有效,或者您有疑问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM