Using a CDN for Tailwind CSS directly in your HTML file isn't the best practice for production. Here's a breakdown of the problems and a recommended solution using a build process:
Problems with Direct CDN Inclusion:
- Performance: Fetching Tailwind CSS from a CDN adds an extra HTTP request to your page load, slowing down initial rendering.
- Bundle Size: The entire Tailwind CSS library is included in your HTML, adding unnecessary weight to your page.
- Customization: It's not ideal for customizing Tailwind's defaults, as you'll need to modify the CDN's version directly.
- Cache Busting: You might not have control over the caching of the CDN, leading to issues with updates.
Best Practices: Build Process (with Vite or Parcel)
-
Project Setup:
- Vite: (Recommended) Create a Vite project:
npm init vite@latest my-project cd my-project
- Parcel:
npm init parcel@latest my-project cd my-project
- Vite: (Recommended) Create a Vite project:
-
Install Tailwind CSS:
- Using npm:
npm install -D tailwindcss postcss autoprefixer
- Using npm:
-
Configure Tailwind:
- Create
tailwind.config.js
:/** @type {import('tailwindcss').Config} */ module.exports = { content: [ "./index.html", "./src/**/*.{vue,js,ts,jsx,tsx}", ], theme: { extend: {}, }, plugins: [], };
- Create
-
Generate CSS:
- Run Tailwind's CLI:
npx tailwindcss -i ./src/index.css -o ./dist/output.css --watch
- Run Tailwind's CLI:
-
Import CSS:
- In
index.html
:<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>My Project</title> <link rel="stylesheet" href="dist/output.css"> </head> <body> <script src="dist/main.js"></script> </body> </html>
- In
Development and Production Environments:
- Vite:
- Development:
- Vite automatically provides hot reloading for CSS changes.
- Production:
npm run build
creates an optimized build in thedist
folder.
- Development:
- Parcel:
- Development:
- Parcel starts a development server, and CSS changes are automatically reflected.
- Production:
npm run build
creates a production-ready build in thedist
folder.
- Development:
Important Notes:
- JavaScript Bundle: Vite or Parcel will also bundle your JavaScript (
main.js
) to improve performance. - CSS Optimization: The build process compresses and minifies your Tailwind CSS for smaller file sizes.
- Server-Side Rendering (SSR): If you're using a server-side framework (e.g., Next.js), you'll typically have a different build setup tailored to that framework.
Example with Vite
# Project setup
npm init vite@latest my-project
cd my-project
# Install dependencies
npm install -D tailwindcss postcss autoprefixer
# Configure Tailwind (create tailwind.config.js)
npx tailwindcss init -p
# Start development server
npm run dev
# Build for production
npm run build
Thank you.