PurgeCSS
“/config/webpack/process-purgecss.js” script runs during gitlab ci production build after Webpack and removes unused styles from specified CSS files.
Script will basically do:
- Create a tree of all Rails templates (Haml, Erb, etc) by parsing all “render partial:” calls recursively, beginning from the first template rendered by Rails action. Which will give list of files like
["/powr/app/views/auto_docs/show.html.haml", "/powr/app/views/auto_docs/_show-new_SEO_tutorials_group_b.html.haml", "/powr/app/views/auto_docs/_show-new_SEO_tutorials_group_control.html.ham", ...]
- Create tree of all JS, JSX (except SCSS) modules used on some particular page (e.g. on tutorial pages) by using tool like https://github.com/pahen/madge
- Run PurgeCSS (https://purgecss.com/CLI.html#usage) CLI for each CSS file generated by Webpack (e.g. “/powr/public/assets/packs/auto_docs-show-e37e301bc900ba6cde8d.css”) and replace that CSS with purged one
where “--content” option will be passed all files (Erb, Haml, JS, etc) from steps 1, 2
Running purgecss locally
To test purgecss in dev environment pls apply following changes to files https://gitlab.com/powr/powr/-/merge_requests/6730 and run command
NODE_ENV=development node --max-old-space-size=8192 node_modules/.bin/webpack --watch --progress --color --config='config/webpack/development.js' --mode=none --build-delimiter='=== Webpack Build Done ==='
Notes
Currently script only traverses rails templates containing string “= render” like
1. <code><em>= render <strong>:partial </strong>=> <strong>'...'</strong></em></code>
2. <strong><code>= <em>render </em>'...'</code></strong>
And helper methods that are used in purgecss should be replaced with “= render” version
In order to make script work correctly with dynamic classes, they should be specified as comments in JS, JSX, Haml, Erb and other template files.