Requirements: In a project, almost all front-end frameworks are referenced, such as: TailwindCSS, Bootstrap, MaterializeCSS, Foundation, etc., we may only use some of the CSS styles in it, and when publishing, we can delete unused CSS code, thusSpeed up website access, save bandwidth and browser memoryWait.
PurgeCSS is a tool for removing unused CSS. It can be part of your development workflow. When you build a website, you may decide to use a CSS framework like TailwindCSS, Bootstrap, MaterializeCSS, Foundation, etc...... But you'll only use a small portion of the framework and will contain a lot of unused CSS styles.
This is where PurgeCSS comes into play. PurgeCSS analyzes your content and CSS files. It then matches the selectors used in the file with those in the content file. It removes unused selectors from CSS, resulting in smaller CSS files.
Website:The hyperlink login is visible. GitHub address:The hyperlink login is visible.
First, we can install the PurgeCSS package globally using npm with the following command:
Create a new ASP.NET Core MVC project using VS, and the project will use the Bootstrap 5 style by default and load in the browserbootstrap.min.cssFile size163kb, the start project is as follows:
Start optimizing with PurgeCSS, creating a new one in the project rootpurgecss.config.jsThe configuration file reads as follows:
The PurgeCSS configuration file reference is as follows:
interface UserDefinedOptions { content: Array<string | RawContent>; css: Array<string | RawCSS>; defaultExtractor?: ExtractorFunction; extractors?: Array<Extractors>; fontFace?: boolean; keyframes?: boolean; output?: string; rejected?: boolean; rejectedCss?: boolean; stdin?: boolean; stdout?: boolean; variables?: boolean; safelist?: UserDefinedSafelist; blocklist?: StringRegExpArray;
}
interface RawContent { extension: string raw: string
}
interface RawCSS { raw: string
}
type StringRegExpArray = Array<RegExp | string>;
type ComplexSafelist = { standard?: StringRegExpArray; deep?: RegExp[]; greedy?: RegExp[]; variables?: StringRegExpArray; keyframes?: StringRegExpArray; };
type UserDefinedSafelist = StringRegExpArray | ComplexSafelist; Publish the ASP.NET Core to a folder and use PurgeCSS to remove unused CSS styles via the command line, the code is as follows:
As shown below:
Start the published project and view it in your browserbootstrap.min.cssThe optimized size is20.8 kb, as shown in the figure below:
This means that the bootstrap.min.css source file size is 163kb, and we only use the 20.8kb class style inside, and PurgeCSS helps us142 kb of content was removed。
(End) |