Using Tailwind CSS with Preprocessors
Overviewβ
This guide provides instructions on how to integrate Tailwind CSS with common CSS preprocessors such as Sass, Less, and Stylus. Since Tailwind is a PostCSS plugin, it can be easily used with these preprocessors, though it is generally recommended to rely on PostCSS plugins for added functionality.
Using PostCSS as Your Preprocessorβ
Benefitsβ
- Faster builds due to fewer processing steps.
- Avoids quirks from mixing Tailwind with preprocessors.
Build-time Importsβ
Use postcss-import
for handling @import
statements:
npm install -D postcss-import
// postcss.config.js
module.exports = {
plugins: {
"postcss-import": {},
tailwindcss: {},
autoprefixer: {},
},
};
Using Sass with Tailwind CSSβ
Installationβ
Install the necessary dependencies:
npm install -D tailwindcss postcss autoprefixer sass
Configurationβ
Create a postcss.config.js
file:
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};
Update your build script to process Sass files:
npx sass src/styles.scss src/styles.css
npx postcss src/styles.css -o dist/styles.css
Example styles.scss
β
@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";
// Custom Sass code
Using Less with Tailwind CSSβ
Installationβ
Install the necessary dependencies:
npm install -D tailwindcss postcss autoprefixer less
Configurationβ
Create a postcss.config.js
file:
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};
Update your build script to process Less files:
npx lessc src/styles.less src/styles.css
npx postcss src/styles.css -o dist/styles.css
Example styles.less
β
@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";
// Custom Less code
Using Stylus with Tailwind CSSβ
Installationβ
Install the necessary dependencies:
npm install -D tailwindcss postcss autoprefixer stylus
Configurationβ
Create a postcss.config.js
file:
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};
Update your build script to process Stylus files:
npx stylus src/styles.styl -o src/styles.css
npx postcss src/styles.css -o dist/styles.css
Example styles.styl
β
@import 'tailwindcss/base'
@import 'tailwindcss/components'
@import 'tailwindcss/utilities'
// Custom Stylus code
Conclusionβ
By following these instructions, you can seamlessly integrate Tailwind CSS with Sass, Less, or Stylus preprocessors in your project. While PostCSS is recommended for most use cases, these steps ensure flexibility for developers working with various preprocessing tools.