In this article, we will talk about how to create an application using Next.js, Tailwind CSS and TypeScript. This blog will also provide a walkthrough on how to use Purgecss to remove unused CSS styles. Let’s get started-
Step 1: Bootstrap the project with Create Next App
In order to set up the boilerplate for the Next.js web app, we have to use Create Next app - the Next.js equivalent of Create React App. We will be using this along with with-typescript from the Next.js example project repo to set up TypeScript. Use the following code-
Step 2: Install Tailwind CSS Dependencies
Now, let’s install the Tailwind packages.
We can also optionally create
a tailwind.config.js
file
with the help of npx to run the Tailwind CLI.
npx tailwind init
Step 3: Setup PostCSS Build
Once Tailwind is installed, we have to set it up to be created with PostCSS.
First, we have to configure the config file.
touch postcss.config.js
Now, we have to add Tailwind and the PostCSS Webpack preset to the plugins section.
The PostCSS plugin system requires the plugins to be added as the string type.
Step 4: Add Tailwind to CSS file
Now, that the setup is done,
we can focus on getting the CSS into
Next.js.
First,
we need to configure
a styles directory
and an index.css
file.
mkdir styles; touch styles/index.css
We can use the @tailwind
directive to insert the base, components,
and utilities styles within the CSS file.
Step 5: Import Global CSS
Now, we have to import index.css
file
into a component so Tailwind
can be utilized all over the app.
Note: We can only import stylesheets
in the pages/_app.{js,ts,jsx,tsx}
file.
Since we’re using TypeScript,
we have to build an app.tsx
file.
touch pages/_app.tsx
Within the _app.tsx
file,
we have to create a custom App component
that will be passed as AppProps
and will import the index.css
file.
Now the entire web app can access the Tailwind CSS classes!
Step 6: Configure Purgecss (Optional)
Here, the major trick is to reduce the CSS file size. One of the simplest ways to reduce the file size is to leverage Purgecss to remove any unrequired styles from the final CSS file.
To set up Purgecss, first, we have to install it, using the following code.
Once done, we can add the plugin and make it run through the CSS class names in all JavaScript and TypeScript files in the pages and components directories. If there is a class name that isn’t used in any of these files, it will simply remove the respective styles from the CSS file.
We can also ensure that Purgecss is only added in production.
Finally, we have to select the base and components styles and mark them as positive, so that Purgecss doesn’t remove them.
Here, we can use a comment to mark them positive in both the sections at the same time.
Final Thoughts
We hope this blog was helpful! To know more, check out the Github repo to view the source code for the final boilerplate.