Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setup PostCSS nesting in Vite?

This is what I’ve tried so far:

  1. Installed via npm install postcss-nesting --save-dev

  2. Setup vite.config.js:

import { fileURLToPath, URL } from 'url';
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import postcssNesting from 'postcss-nesting';

export default defineConfig({
    plugins: [
        vue(),
        postcssNesting
    ],
  
    resolve: {
        alias: {
            '@': fileURLToPath(new URL('./src', import.meta.url))
        }
    }
});

But it’s not working. What’s the right way to setup PostCSS so that I can use CSS nesting?

like image 231
NicOwen Avatar asked Jan 20 '26 03:01

NicOwen


2 Answers

I was able to get it work like this:

import { defineConfig } from "vite";
import postcssNesting from 'postcss-nesting';

export default defineConfig({
    css: {
        postcss: {
            plugins: [
                postcssNesting
            ],
        },
    },
});
like image 196
Fred Yankowski Avatar answered Jan 23 '26 02:01

Fred Yankowski


Just create a file on the root of your project called postcss.config.js:

module.exports = {
  plugins: {
    'postcss-nesting': { /* plugin options */ },
  },
}

Vite uses postcss-load-config which means that it can pick up the postcss config file (file name can be one of the many formats supported by this package e.g. postcss.config.js, .postcssrc, .postcssrc.js etc).


If you want nesting with PostCSS just like you do it in SASS, I suggest you use postcss-nested.

If you want to use it together with TailwindCSS, you don't have to install it since it's included directly in the tailwindcss package itself:

// postcss.config.js
module.exports = {
  plugins: {
    'tailwindcss/nesting': {},
    tailwindcss: {},
    autoprefixer: {},
  }
}

TailwindDocs: Nesting

like image 33
Roland Avatar answered Jan 23 '26 00:01

Roland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!