I'm building a Vue 3 component library using Vite and Tailwind CSS, but I want to ensure that the final build only includes the Tailwind classes that are actually used in my components.
Right now, the entire Tailwind CSS framework is being bundled, which significantly increases the file size.
When I build the package, the entire Tailwind CSS framework is included, even though I only use a small set of classes.
I want tree-shaking/purging in the config so that only the used Tailwind classes are included in the final dist/ output
My file structure:
eslint.config.mjs
LICENSE
package-lock.json
package.json
packages
├── image-editor-vue
│ ├── package.json
│ ├── src
│ │ ├── components
│ │ │ ├── Button
│ │ │ │ ├── Button.vue
│ │ │ │ ├── types.ts
│ │ │ │ ├── useButton.ts
│ │ ├── index.css
│ │ ├── index.ts
│ │ ├── shims-vue.d.ts
│ │ ├── vite-env.d.ts
│ ├── tsconfig.json
│ ├── vite.config.ts
playground
README.md
scripts
├── release.ts
tsconfig.config.json
tsconfig.json
packages/image-editor-vue/package.json
import { resolve } from 'node:path'
import tailwindcss from '@tailwindcss/vite'
import Vue from '@vitejs/plugin-vue'
import { defineConfig } from 'vite'
import Dts from 'vite-plugin-dts'
export default defineConfig({
plugins: [
Vue(),
Dts({
tsconfigPath: './tsconfig.json',
}),
tailwindcss(),
],
build: {
target: 'es2015',
minify: false,
copyPublicDir: false,
outDir: 'dist/',
lib: {
name: '@hetari/image-editor-vue',
entry: {
index: resolve(__dirname, 'src/index.ts'),
},
formats: ['es'],
},
rollupOptions: {
external: ['vue', 'tailwindcss'],
output: {
exports: 'named',
globals: {
vue: 'Vue',
tailwindcss: 'tailwindcss',
assetFileNames: 'style.css',
},
},
},
},
})
How can I configure Tailwind CSS or Vite to remove unused styles in my library?
.gitignore
Regardless, it is important to understand how Tailwind CSS works. By default, it creates an empty build and uses automatic source detection to scan your HTML, JS, and other files for class names. Any detected classes are included in the final build.
It's important to note that Tailwind CSS skips any paths listed in your .gitignore
file. At this point, it's crucial to create a .gitignore
file that at least excludes the /node_modules/
directory to prevent Tailwind from detecting its own files.
packages/image-editor-vue/.gitignore
/node_modules/
/dist/
Tailwind CSS only includes the classes that are actually used in the final compiled CSS. However, (when using .gitignore
and exclude /node_modules/
...) there are some known issues that may cause a few extra colors and classes to be included in the build, but not everything-only around 10-20KB of additional data.
I recommend using PurgeCSS alongside Tailwind CSS, as it can instantly and easily reduce the size of the compiled CSS.