2.Mangle
Introduction
<!-- Before modification -->
<div class="z-10 w-full max-w-5xl items-center justify-between font-mono text-sm lg:flex"></div>
<!-- After modification -->
<div class="tw-g tw-h tw-i tw-d tw-e tw-j tw-k tw-l"></div>Usage
1. Install Packages
npm i -D unplugin-tailwindcss-mangle tailwindcss-patch2. Run the Installation Script
npx tw-patch install3. Add prepare Script in package.json
"scripts": {
"prepare": "tw-patch install"
},4. Run the Extraction Command
Navigate to the directory containing package.json and tailwind.config.js, then run:
npx tw-patch extractCheck out more options in tailwindcss-patch
This will generate a JSON file: .tw-patch/tw-class-list.json
5. Register the Plugin
vite
import vue from '@vitejs/plugin-vue'
import utwm from 'unplugin-tailwindcss-mangle/vite'
// For example: a vue vite project
import { defineConfig } from 'vite'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue(), utwm()]
})Then run the script:
# Generate build package
yarn build
# Preview
yarn previewYou will see all class names renamed to tw-*
webpack
// esm
import { webpackPlugin as utwm } from 'unplugin-tailwindcss-mangle'
// or cjs
const utwm = require('unplugin-tailwindcss-mangle/webpack')
// Use this webpack plugin
// For example next.config.js
const { defineConfig } = require('@vue/cli-service')
// vue.config.js
module.exports = defineConfig({
transpileDependencies: true,
configureWebpack: (config) => {
if (process.env.NODE_ENV === 'production') {
config.plugins.push(utwm())
}
}
})
Notes
This plugin will only transform utility classes containing - or :, such as w-32, before:h-[300px], after:dark:via-[#0141ff]/40. Some class names like flex, relative will not be transformed.
Because the plugin will traverse all html class attributes and class names in js literals, looking for utility classes generated by tailwindcss.
Transforming js literals like the following is dangerous:
const innerHTML = 'i\'m flex and relative and grid'
document.body.innerHTML = innerHTMLTherefore, only strings containing - or : will be transformed.
Additionally, the plugin provides an option twIgnore to skip Mangle for certain strings.
For example:
Input
const twIgnore = String.raw;
const className = `${twIgnore`gap-y-4`} bg-zinc-800/30`;Output
const twIgnore = String.raw;
const className = `${twIgnore`gap-y-4`} tw-a`;