Want to speed up your web development and keep designs consistent? Here's how to create and use reusable Tailwind CSS components across projects:
- Set up your workspace with VS Code, Node.js, and Tailwind CSS
- Create a component library using @apply or React components
- Share components via npm packages, monorepos, or Git submodules
- Use design tokens and shared config files for consistency
- Optimize performance with JIT mode and lazy loading
Here's a quick comparison of sharing methods:
Method | Pros | Cons |
---|---|---|
npm packages | Easy to distribute | Version management |
Monorepo | Everything in one place | Complex setup |
Git submodules | Independent updates | Can be tricky to manage |
By reusing Tailwind components, you'll save time, maintain consistency, and focus on building unique features. Let's dive in and learn how to make it happen.
Related video from YouTube
What are reusable components?
Reusable components in Tailwind CSS are pre-built UI elements you can use in multiple projects. Think of them as LEGO blocks for web design - they help you build faster and keep things consistent.
Why use them?
Here's why reusable components are awesome:
- Save time (no reinventing the wheel)
- Keep your design consistent
- Update once, see changes everywhere
- Smaller file sizes = faster loading
- Focus on the cool, unique stuff instead of basic elements
For example, Mojro (a logistics company) uses the same components across different portals. This way, trip data looks the same everywhere, and updates are a breeze.
Watch out for these issues
Reusable components aren't perfect. Here are some common hiccups:
- Getting too cozy with one environment
- Making them flexible enough (but not TOO flexible)
- Updating without breaking stuff
- Keeping track of different versions
To tackle these, use tools like VS Code with Tailwind CSS Intellisense. Libraries like clsx
can also help make your components more adaptable.
Here's a quick example of a reusable Card component using React and Tailwind CSS:
import * as React from "react";
import clsx from "clsx";
const Card = React.forwardRef(({ className, ...props }, ref) => (
<div
ref={ref}
className={clsx(
"rounded-lg border bg-slate-100 text-white shadow-sm",
className,
)}
{...props}
/>
));
This card can be easily tweaked for different projects while keeping its core design intact.
Setting up your workspace
Let's get your workspace ready for sharing Tailwind CSS components across projects.
Tools you'll need
You'll need these key tools:
- Visual Studio Code (with Tailwind CSS IntelliSense extension)
- Node.js and npm
- Tailwind CSS
- PostCSS
How to set up Tailwind CSS
Here's how to get Tailwind CSS running:
1. Create a project directory and open it in VS Code.
2. In your terminal, run:
npm init -y
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
3. In tailwind.config.js
, add your template paths:
module.exports = {
content: ["./src/**/*.{html,js,jsx,ts,tsx}"],
theme: {
extend: {},
},
plugins: [],
}
4. Create src/styles.css
with Tailwind directives:
@tailwind base;
@tailwind components;
@tailwind utilities;
5. Add this build script to package.json
:
"scripts": {
"build": "tailwindcss -i src/styles.css -o dist/output.css --watch"
}
6. Run npm run build
to start the Tailwind CSS build process.
That's it! You're now set up to create and share Tailwind CSS components across your projects.
How to create reusable Tailwind components
Want to speed up your workflow and keep your projects consistent? Here's how to make reusable Tailwind CSS components:
Spot common patterns
First, look for UI elements you use a lot. Buttons, cards, nav bars - that kind of thing. Once you've found these repeating patterns, you can turn them into multi-purpose components.
Take this button, for example:
<button class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600">
Click me
</button>
Use @apply
Tailwind's @apply
directive lets you bundle utility classes into reusable CSS classes. It's perfect for small, frequent components.
Here's how to make a reusable button class:
@layer components {
.btn-blue {
@apply px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600;
}
}
Now you can use it like this:
<button class="btn-blue">Click me</button>
Build a component library
Want to go bigger? Here's how:
- Make a
components
folder in yoursrc
directory. - For each component, create two files:
ComponentName.tsx
andComponentName.stories.tsx
. - Use TypeScript for better maintainability. Here's a Button component example:
// Button.tsx
import React from 'react';
interface ButtonProps {
text: string;
type?: 'primary' | 'secondary';
onClick?: () => void;
}
export const Button: React.FC<ButtonProps> = ({ text, type = 'primary', onClick }) => {
const buttonClasses = type === 'primary'
? 'bg-blue-500 hover:bg-blue-600 text-white'
: 'bg-gray-200 hover:bg-gray-300 text-black';
return (
<button
className={`px-4 py-2 rounded ${buttonClasses}`}
onClick={onClick}
>
{text}
</button>
);
};
- Use Storybook to showcase and test your components.
- Create an
index.ts
file to export all components:
// index.ts
export * from './Button/Button';
// Add other component exports here
And there you have it! You're now set up to create and use reusable Tailwind components. Happy coding!
sbb-itb-55aadfa
Ways to share components between projects
Want to share Tailwind CSS components across projects? Here are three methods that work:
Npm packages
Create an npm package to share components. Here's how:
1. Set up your package
Run npm init
. Pick a unique package name.
2. Configure your build
Use Rollup. Create rollup.config.js
:
import postcss from 'rollup-plugin-postcss'
export default {
input: 'src/index.js',
output: {
file: 'dist/bundle.js',
format: 'cjs'
},
plugins: [
postcss({
plugins: [
require('tailwindcss'),
require('autoprefixer'),
]
})
]
}
3. Publish
Run npm publish --access public
.
Monorepo setup
Keep all projects in one repo. Structure it like this:
my-monorepo/
├── packages/
│ ├── ui-components/
│ │ ├── src/
│ │ └── package.json
│ └── web-app/
│ ├── src/
│ └── package.json
└── package.json
Use PNPM or Turborepo to manage your monorepo.
Git submodules
Include one repo inside another. Add a component repo as a submodule:
git submodule add git@github.com:your-username/your-component-repo.git
This keeps components updated independently.
Each method has its ups and downs. Pick based on your team and project needs.
Keeping designs consistent across projects
Want to keep your Tailwind CSS components looking the same in different projects? Here's how:
Design tokens: Your design building blocks
Design tokens are like the DNA of your design system. They store all your colors, spacing, and typography in one place. Here's how to use them:
1. Create a tokens.json
file:
{
"colors": {
"primary": "#1a202c",
"secondary": "#2d3748"
},
"spacing": {
"small": "4px",
"medium": "8px",
"large": "16px"
},
"fontSizes": {
"small": "12px",
"base": "16px",
"large": "24px"
}
}
2. Use these tokens in your tailwind.config.js
:
const tokens = require('./tokens.json');
module.exports = {
theme: {
extend: {
colors: tokens.colors,
spacing: tokens.spacing,
fontSize: tokens.fontSizes,
},
},
};
Now you can change your design in one place and see it update everywhere. Magic!
Shared config files: One config to rule them all
Want all your projects to start with the same styles? Use a shared config file:
- Create a base
tailwind.config.js
somewhere central. - In each project, import and extend this base:
const baseConfig = require('../path/to/base-tailwind.config.js');
module.exports = {
...baseConfig,
// Add any project-specific tweaks here
};
This way, all your projects start on the same page, but you can still make changes when needed.
Tailwind's prefix option: No more style clashes
Worried about styles from different projects fighting? Use Tailwind's prefix feature:
module.exports = {
prefix: 'proj-',
// The rest of your config
};
Now your classes will look like proj-text-lg
instead of just text-lg
. No more style wars!
Making components work faster
Want to speed up your Tailwind CSS components? Let's focus on two key areas:
- Getting rid of styles you don't use
- Loading components only when you need them
Cutting the fat: Removing unused styles
Tailwind CSS comes with a TON of utility classes. But chances are, you're only using a small chunk of them. Here's how to slim down your CSS:
- Turn on Just-in-Time (JIT) mode in your
tailwind.config.js
:
module.exports = {
mode: 'jit',
content: ['./src/**/*.{html,js}'],
// other config
}
JIT mode is like a personal tailor for your CSS. It only creates the styles you actually use.
// webpack.mix.js
const mix = require('laravel-mix');
require('laravel-mix-purgecss');
mix.sass('resources/sass/app.scss', 'public/css')
.purgeCss({
content: ['./src/**/*.html', './src/**/*.vue', './src/**/*.jsx'],
});
These steps can DRAMATICALLY shrink your CSS file. Just look at Netflix's "Top 10" site - they use Tailwind and only send 6.5kB of CSS over the wire!
Loading components on demand
Lazy loading is like calling an Uber - it only shows up when you need it. Here's how to do it in React:
import React, { Suspense, lazy } from "react";
const LazyComponent = lazy(() => import("./LazyComponent"));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
);
}
This trick loads components only when necessary, giving your initial page load a serious speed boost.
Conclusion
Reusing Tailwind CSS components across projects can speed up your work and keep your designs consistent. Here's what to remember:
- Build a component library
- Share components efficiently
- Keep designs consistent
- Optimize for performance
The future of Tailwind CSS component sharing looks promising. With more companies using Tailwind, we'll likely see more community-driven libraries and better tools. We might even see AI helping to create and improve components.
"If you're on the fence about adopting it, remember that aptitude often begins with experimentation." - Luis Minvielle, Author at .cult
This quote captures the spirit of Tailwind CSS. As developers keep pushing boundaries, we can expect exciting new developments in the Tailwind ecosystem.