How to configure Tailwind CSS to have small size in Phoenix application
April 04, 2020
Tailwind CSS is utility first css framework. It is very useful, once the initial learning curve is crossed over. However, one of the biggest issues with Tailwind CSS is, by default, generated css asset will be quite big, up to 1MB, and sometimes more.
Solution suggested by Tailwind CSS team is to use tool called Purgecss. It will remove all CSS classes that are not used in the project.
Setting up Purgecss
First, we need to instal npm package of purgecss
.
npm install @fullhuman/postcss-purgecss --save-dev# oryarn add @fullhuman/postcss-purgecss --save-dev -D
Next, we need to configure our assets/postcss.config.js
file
const purgecss = require("@fullhuman/postcss-purgecss")({//File paths to all templates in our project.content: ["../lib/**/*.eex", "../lib/**/*.leex"],//Regular expression with each classes are determineddefaultExtractor: (content) => content.match(/[\w-/:]+(?<!:)/g) || [],})module.exports = {plugins: [require("tailwindcss"),require("autoprefixer"),// We are adding purgecss only for production builds...(process.env.NODE_ENV === "production" ? [purgecss] : []),],}
One thing to note, purgecss
will look for any string, that matches the regular expression above, so it is important to make sure, that class names are not created dynamically.
Snippet below is not correct
<divclass="bg<%= if is_saved?(@var) do %>red<% else %>green<% end %>-100"></div>
Instead, provide complete class names
<divclass="<%= if is_saved?(@var) do %>bg-red-100<% else %>bg-green-100<% end %>"></div>
We are almost there, we added purgecss plugin, we updated our postcss.config.js
file, now we just need to make sure, that when we are preparing assets for production, purgecss plugin is used. For this, we can update deploy
command in package.json
by adding NODE_ENV=production
.
//package.json{..."scripts": {"deploy": "NODE_ENV=production webpack --mode production","watch": "webpack --mode development --watch"}...}
Or, we can also pass NODE_ENV
when we are actually calling the deploy
command.
npm installNODE_ENV=production npm run deploy
Just make sure, you are not setting NODE_ENV
before npm install
command, as it will then install only non-dev dependencies, which we don’t want.
At this point, our generated css file should be a lot smaller compared to the non-purged css file. In my app, generated css file went from over 900kb to 39kb. Of course, this will heavily depend on how many how heavily css classes from Tailwind CSS are used, and custom classes your application has.
For more details on how to further optimize css build, you can visit oficial guide from Tailwind CSS team
If you have any questions, you can ping on twitter