This article will guide you how to install and setup Tailwindcss in your project with production ready minimal size of the final build.
From tailwindcss website:
Before we start to install and setup tailwindcss in a project, make sure you have installed Nodejs version 12.13.0
or higher.
Navigate to your project directory and run the following commands to init Nodejs and install tailwindcss. In my case project directory is /backups/projects/myapp
.
cd /backups/projects/myapp
npm init -y
npm install tailwindcss@latest postcss@latest autoprefixer@latest
After installation you can create two directories like src
where you can put your pre distribution files and dist
to have the final build files.
mkdir src dist
Now create a style.css
file in src
directory and paste this inside.
@tailwind base;
@tailwind components;
@tailwind utilities;
In the root of the project you will have package.json
, open it and change the following line:
"test": "echo \"Error: no test specified\" && exit 1"
to
"build:css" :"tailwind build -i src/style.css -o dist/assets/css/style.css"
I have created sub directories inside dist to organize the project.
Now back to the terminal to build tailwindcss with npm.
npm run build:css
At this point you will have a style.css
file in dist/assets/css/
which you can include in your project head section for example:
<link href="assets/css/style.css" rel="stylesheet">
Note that href
does not start with dist
as the build files are already in dist directory.
But the catch here is the file is huge, more than 3MB and that’s not what we want.
Production ready style.css
In the project root directory create a file tailwind.config.js
and paste this inside:
module.exports = {
purge: {
enabled: true,
content: ['./**/*.{php,html}'],
}
}
This block {php,html}
in the code means to look for the tailwindcss components in php and html files. You can include others according to your need.
Run npm build to rebuild the style.css file.
npm run build:css
Now whatever classes/components you have used in your project files, the final file will only have that and size will be small.