How do I add Tailwindcss to an Ionic React project?
Simon Grimm created a very good tutorial about using Tailwind with Ionic. The tutorial is for angular, but it should not be very complicated to use it in React: How to Use Tailwind with Ionic - YouTube
Can you send over a solution? been stuck on integrating it with react
This post is focused more on Next.js, but is React-focused.
Is there a way to use tailwindcss without NextJS?
There is, yeah. We’re doing just that. I’m not really sure what the real benefit of adding nextjs to the mix is anyhow given that the real advantages of netxjs are things like routing and SSR—neither of which you can use to any significant degree inside an ionic app.
While I don’t have the code neatly packaged up to show you I can give you some pointers.
First, if you used create-react-app
or used ionic itself to create your ionic react project you probably need to use something like craco to allow overriding CRA’s configurations. That will allow you to add tailwind and autoprefixer as postcss plugins.
You’ll also want to change package.json
to use craco
to run react-scripts
.
...
"scripts": {
"start": "craco start",
"build": "craco build",
"test": "craco test",
"eject": "craco eject"
},
...
# craco.config.js
module.exports = {
style: {
postcss: {
plugins: [require("tailwindcss"), require("autoprefixer")],
},
},
};
You’ll also need to add the tailwind directives to src/index.tsx
:
# src/index.css
@tailwind base;
@tailwind components;
@tailwind utilities;
Use tailwind init
to generate a tailwind config. You probably want to use purgecss to drop all the unused classes:
# tailwind.config.js
module.exports = {
purge: ["src/**/*.jsx", "src/**/*.tsx", "src/**/*.html"],
darkMode: false, // or 'media' or 'class'
theme: {
extend: {},
},
variants: {
extend: {},
},
plugins: [],
};
That should get you there.
lightcap solution using craco makes Tailwind works when running the project using craco’s scripts from the package.json
but another problem appears…
When using ionic-cli
Tailwind is not working because ionic-cli
does not use the package.json
scripts to run and build the project, looks like it uses react-scripts
directly.
So could this lead to some problems when building the app for other platforms outside the web via ionic-cli
? There is no way to change this default behavior from ionic-cli
?
Hey @lucas-santosP, I stumbled upon the same issue and could fix it with the comments in this issue: Customize ionic build (e.g. using craco instead of react-scripts) · Issue #4627 · ionic-team/ionic-cli · GitHub
You can just add
"ionic:build": "craco build",
"ionic:serve": "craco start",
to your package.json, to tell ionic cli to use craco for build and start.
You might also want to add this to support platform specific styling and part styling