https://github.com/huygn/tailwind-unit-replace
Helpers to replace TailwindCSS's default REM based units with anything like PX or EM.
https://github.com/huygn/tailwind-unit-replace
css nodejs tailwind tailwindcss
Last synced: 11 months ago
JSON representation
Helpers to replace TailwindCSS's default REM based units with anything like PX or EM.
- Host: GitHub
- URL: https://github.com/huygn/tailwind-unit-replace
- Owner: huygn
- Created: 2021-08-21T12:50:16.000Z (almost 5 years ago)
- Default Branch: main
- Last Pushed: 2023-07-01T08:00:41.000Z (about 3 years ago)
- Last Synced: 2025-07-04T09:17:17.361Z (about 1 year ago)
- Topics: css, nodejs, tailwind, tailwindcss
- Language: TypeScript
- Homepage: http://npm.im/tailwind-unit-replace
- Size: 21.5 KB
- Stars: 10
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# tailwind-unit-replace
[](https://badge.fury.io/js/tailwind-unit-replace)
[](https://github.com/huygn/tailwind-unit-replace/actions/workflows/ci.yml)
Helpers to replace Tailwind's default unit (`rem`) with whatever possible, be it `em`, `px` .etc.
Let's face it, Tailwind's default `rem` unit works great for websites & apps. But if you're building components library or plugins, chances are you'd like your plugin's size/spacing to stay fixed as desired (in `px`) or dynamically based on it's closest ancestor (like `em`). This repo aims to make it possible without hassles.
## Install
```sh
npm i -D tailwind-unit-replace
```
## Usage
```javascript
const { replaceTailwindUnit, toEM, toPX } = require('tailwind-unit-replace')
const config = { ... } // your custom Tailwind config
module.exports = replaceTailwindUnit({
exclude: ['fontFamily'],
replacer: toEM // or `toPX` to convert to pixel (16-based)
})(config)
```
If you'd like to replace unit with a more flexible value, you can write a custom `replacer` - take a look at [toEM](./src/extras.ts)'s implementation, for example this is how I did in another project:
```typescript
function replacer(value: string) {
return value.replace(remUnitRegex, (match, remDigit) => {
const amount = Number(remDigit);
if (Number.isNaN(amount)) return match;
return `calc(var(--root-font-size) * ${amount})`;
});
}
```
`replacer` function will be called on each config (deeply nested) string value, and is expected to return a string value which will be applied to the final replaced Tailwind config.