提示
该文档适用于 PurgeCSS 3.0 及更高版本。要查看 PurgeCSS 2.x 的文档,请点击 此处
安全列出
你可以指出哪些选择器可以安全地保留在最终的 CSS 中。这可以通过 PurgeCSS 选项 safelist 来实现,或者直接在你的 CSS 中使用特殊注释来实现。
特定选择器
你可以使用 safelist 将选择器添加到安全列表中。
const purgecss = new Purgecss({
content: [], // content
css: [], // css
safelist: ['random', 'yep', 'button']
})
在示例中,选择器 .random、#yep、button 将保留在最终的 CSS 中。
模式
你可以使用 safelist.standard、safelist.deep 和 safelist.greedy 根据正则表达式将选择器列入安全列表。
const purgecss = new Purgecss({
content: [], // content
css: [], // css
safelist: {
standard: [/red$/],
deep: [/blue$/],
greedy: [/yellow$/]
}
})
在示例中,以 red 结尾的选择器(例如 .bg-red)、以 blue 结尾的选择器以及它们的子级(例如 blue p 或 .bg-blue .child-of-bg),以及任何部分以 yellow 结尾的选择器(例如 button.bg-yellow.other-class),都将保留在最终的 CSS 中。
模式是正则表达式。你可以使用 regexr 来验证正则表达式是否与你正在寻找的内容相符。
直接在 CSS 中
你可以使用特殊注释直接在 CSS 中进行安全列示。使用 /* purgecss ignore */ 来安全列示下一条规则。
/* purgecss ignore */
h1 {
color: blue;
}
使用 /* purgecss ignore current */ 来安全列示当前规则。
h1 {
/* purgecss ignore current */
color: blue;
}
你可以使用 /* purgecss start ignore */ 和 /* purgecss end ignore */ 来安全列示一系列规则。
/* purgecss start ignore */
h1 {
color: blue;
}
h3 {
color: green;
}
/* purgecss end ignore */
h4 {
color: purple;
}
/* purgecss start ignore */
h5 {
color: pink;
}
h6 {
color: lightcoral;
}
/* purgecss end ignore */
陷阱
一些 CSS 优化工具,例如 PostCSS 或 cssnano,会在 PurgeCSS 在你的构建过程中运行之前删除注释,这可能会被忽视,因为这些步骤通常在开发中被禁用。为了防止这些注释被删除,你可以用感叹号标记为重要注释。
/*! purgecss start ignore */
h5 {
color: pink;
}
h6 {
color: lightcoral;
}
/*! purgecss end ignore */
