Published on January 2019
3 min read
Originally posted on Medium
Other blog/Medium posts directly tell you to eject from create-react-app, but that’s not needed. Also they don’t discuss about production setup, that’s why I have written this post.
TLDR: You can directly pull the setup from here.
Make a React app using create-react-app
Install Tailwind and PostCSS CLI with
npm i -D tailwindcss postcss-cliMake a Tailwind config using npx tailwind init or ./node_modules/.bin/tailwind init. This command creates tailwind.js at root of your project. NPX comes installed alongwith NodeJS and NPM.
Now create postcss.config.js file at root of your project and write the following
const tailwindcss = require('tailwindcss');
module.exports = {
plugins: [
tailwindcss('./tailwind.js')
]
}@tailwind preflight;
@tailwind components;
@tailwind utilities;@tailwind in tailwind-own.css is not valid CSS, we will use POSTCSS to transform this tailwind-own.css to valid CSS in tailwind.css which will then be imported and used by React app.import './tailwind.css';scripts of package.json to include command which runs POSTCSS in watch mode. In the code below, start:tw takes in src/tailwind-own.css and outputs src/tailwind.css which contains valid CSS, and as you have imported tailwind.css in your index.js, you will get all Tailwind utility classes. -w in start:tw enables watch mode, so it will watch for any changes in tailwind-own.css and will remake tailwind.css accordingly."scripts": {
"start:tw": "postcss ./src/tailwind-own.css -o ./src/tailwind.css -w",
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},start:tw and and other to run React app as usual.npm run start:twnpm startTry running npm run build. You’ll see 35KB+ of CSS being generated even if you have used two classes or so.
We will use PurgeCSS to strip all unused CSS. Install it with
npm i -D @fullhuman/postcss-purgecssNow change your postcss.config.js which you had created to include code which removes unused CSS for production.
const tailwindcss = require('tailwindcss');
const purgecss = require('@fullhuman/postcss-purgecss');
module.exports = {
plugins: [
tailwindcss('./tailwind.js'),
process.env.NODE_ENV==="production" && purgecss({
content: ['./src/**/*.js'],
css: ['./src/**/*.css'],
})
]
}content denotes the places where you have used CSS classes.
Also add this line in “scripts” of your package.json
"build:tw": "postcss ./src/tailwind-own.css -o ./src/tailwind.css --env production"Now to build it for production, we first need to run
npm run build:twwhich creates stripped tailwind.css and then we will run
npm run buildto get out our production files.
Now look at CSS bundle size. It will be a few KBs or so. Nice.
As said at starting of this post, if you don’t want to setup all this you can go to this repo and download React app which has all this pre-configured.