2.Mangle

2. Mangle

Feature Overview

<!-- Before -->
<div class="z-10 w-full max-w-5xl items-center justify-between font-mono text-sm lg:flex"></div>
<!-- After -->
<div class="tw-g tw-h tw-i tw-d tw-e tw-j tw-k tw-l"></div>

Usage

1. Install the package

npm i -D unplugin-tailwindcss-mangle tailwindcss-patch

2. Run the installation script

npx tw-patch install

3. Add the prepare script in package.json

  "scripts": {
    "prepare": "tw-patch install"
  },

4. Run the extraction command

Navigate to the same directory as your package.json and tailwind.config.js, then run:

npx tw-patch extract

See more options in tailwindcss-patch

This will generate a JSON file: .tw-patch/tw-class-list.json

5. Register this plugin

vite

import vue from '@vitejs/plugin-vue'
import utwm from 'unplugin-tailwindcss-mangle/vite'
// For example: vue vite project
import { defineConfig } from 'vite'
// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue(), utwm()]
})

Then run the script:

# Build the package
yarn build
# Preview
yarn preview

You will see that all class names are 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 in 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 only transforms utility class names that contain - or :, such as w-32, before:h-[300px], after:dark:via-[#0141ff]/40. Some class names like flex, relative will not be transformed.

The plugin traverses all html class attributes and js string literals to find the utility classes generated by tailwindcss.

Transforming string literals like the following in js is dangerous:

const innerHTML = 'i\'m flex and relative and grid'
document.body.innerHTML = innerHTML

Thus, only strings containing - or : will be transformed.

Additionally, the plugin provides the twIgnore option, which allows some strings to be skipped during the Mangle.

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`;