Let’s install PostCSS Nesting (or any PostCSS Plugin) in our Vite based Ionic project!
PostCSS Nesting over Native Nesting
Native CSS Nesting is nearly here, but it’s going to be a little while yet before every user is able to render it, especially if you’re building an ionic app that targets “older” devices. So it’s probably wiser to continue using third party solutions for the forseeable future.
I’ve always been a SASS user up until now, but the advantage of using PostCSS Nesting is that it uses the W3C CSS Nesting spec, so that when the time comes to target only devices that can handle CSS Nesting the switch should be as simple as uninstalling the plugins and deleting the config file.
Installing PostCSS Load Config
Conveniently, PostCSS Plugins are very modular. However all of them require you to have installed PostCSS Load Config & PostCSS Plugin
npm i -D postcss-load-config postcss-plugin
Then we need to create the config file. Make a file named .postcssrc.json
in the root of your project with the following contents
{
"plugins": {
"postcss-plugin": {},
"postcss-nesting": {} // omit this if not installing nesting
}
}
Installing Plugins
Once you’ve installed Load Config and added the config file, you can browse their extensive plugin collection, but we’re interestined in their nesting plugin. Install it with
npm i -D postcss postcss-nesting
That should be everything! Add some CSS nesting to one of your stylesheets
.Component {
color: red;
h1 {
color: blue;
}
}
and run ionic server
to get going. No further work required!