![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/smastrom/vite-plugin-unused-css-vars/tests.yml?branch=main&label=tests)
Vite Plugin Unused CSS Variables
A simple Vite plugin that removes unused variables from your bundled CSS files using lightningcss custom transforms.
:warning: Please note that this plugin only works with vite build
command and not vite dev
.
Installation
npm i --save-dev vite-plugin-unused-css-vars lightningcss
Usage
import { defineConfig } from 'vite'
import unusedCssVars from 'vite-plugin-unused-css-vars'
export default defineConfig({
plugins: [unusedCssVars()],
})
How it works
The plugin looks for variable declarations and references across all chunks bundled by Rollup:
:root {
--used-var: #fff;
}
.my-class {
color: var(--used-var);
}
If a variable is never referenced, all its declarations are stripped away from any chunk that contains them:
:root {
--unused-var: #fff;
}
The plugin doesn't perform any transpilation or additional processing; think of it as a find/replace operation on the files that will be shipped to the browser.
Logging removals
Enable the log
option to see which variables were removed:
export default defineConfig({
plugins: [
unusedCssVars({
log: true,
}),
],
})
Excluding variables
Pass an array of variable names to the exclude
option to prevent them from being removed:
export default defineConfig({
plugins: [
unusedCssVars({
exclude: ['--color'],
}),
],
})
Minification
By default, this plugin assumes that your files are minified and will perform the minification again when rewriting files that contains unused variables.
In case you are not emitting minified files, you can disable this behavior by passing false
to the minify
option:
export default defineConfig({
plugins: [
unusedCssVars({
minify: false,
}),
],
})
Limitations
JS-injected CSS (Framework-specific)
Some frameworks may not always output CSS files but instead generate a JS file that injects the styles directly in the HTML.
An example of this is Nuxt, when using the css
option in nuxt.config.js
:
export default defineNuxtConfig({
css: ['@/assets/variables.css'],
})
In this case the plugin won't be able to remove unused variables, as it only works by reading CSS files.
For this specific case, import the file in your default.vue
layout or app.vue
component to make sure it's bundled as a CSS file:
<script setup>
import '@/assets/variables.css'
</script>
HTML-referenced variables
If you are referencing CSS variables directly in your HTML, the plugin won't be able to detect
the references and will remove their declarations:
<div class="my-var" style="color: var(--color);"></div>
.my-var {
--color: red;
}
In such case, you might want to exclude those variables from being removed.
License
MIT