or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-jss-plugin-default-unit

JSS plugin that adds default custom unit to numeric values where needed

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/jss-plugin-default-unit@10.10.x

To install, run

npx @tessl/cli install tessl/npm-jss-plugin-default-unit@10.10.0

index.mddocs/

JSS Plugin Default Unit

JSS Plugin Default Unit automatically adds default CSS units to numeric values in JavaScript style objects. It eliminates the need to manually specify units like 'px', 'ms', or '%' for most CSS properties, providing a comprehensive mapping of CSS properties to their appropriate default units.

Package Information

  • Package Name: jss-plugin-default-unit
  • Package Type: npm
  • Language: JavaScript with TypeScript definitions
  • Installation: npm install jss-plugin-default-unit

Core Imports

import defaultUnit from "jss-plugin-default-unit";

For CommonJS:

const defaultUnit = require("jss-plugin-default-unit");

Basic Usage

import { create } from "jss";
import defaultUnit from "jss-plugin-default-unit";

// Create JSS instance with default unit plugin
const jss = create().use(defaultUnit());

// Create styles with numeric values - units are added automatically
const sheet = jss.createStyleSheet({
  button: {
    width: 100,        // becomes "100px"
    height: 50,        // becomes "50px"  
    margin: 10,        // becomes "10px"
    borderRadius: 5,   // becomes "5px"
    animationDuration: 300  // becomes "300ms"
  }
});

Architecture

The plugin operates through JSS's plugin lifecycle hooks, implementing two key methods:

  • onProcessStyle: Processes entire style objects during rule creation, recursively applying units to numeric values
  • onChangeValue: Handles individual property value changes during dynamic updates

Core Components:

  • Unit Mapping System: Comprehensive mapping of 170+ CSS properties to their default units (px, ms, %)
  • Property Name Normalization: Supports both kebab-case and camelCase CSS property names through automatic conversion
  • Recursive Processing: Handles nested objects (media queries, fallbacks) and arrays (multiple values)
  • CSS Typed OM Integration: Uses CSS Typed OM when available for improved performance, falls back to string units

Processing Flow:

  1. User provides numeric values in style objects
  2. Plugin identifies the CSS property name (normalizing case)
  3. Looks up default unit from internal mapping or custom options
  4. Applies unit to numeric values (with special handling for zero values)
  5. Recursively processes nested structures

Capabilities

Plugin Factory Function

Creates a JSS plugin instance that adds default units to numeric CSS values.

/**
 * Creates a JSS plugin that adds default units to numeric values
 * @param options - Optional configuration for custom unit overrides
 * @returns JSS Plugin object with onProcessStyle and onChangeValue methods
 */
function defaultUnit(options?: Options): Plugin;

interface Options {
  [propertyName: string]: string | ((value: number) => string);
}

interface Plugin {
  onProcessStyle(style: Object, rule: Rule): Object;
  onChangeValue(value: any, prop: string): any;
}

Usage with custom options:

import defaultUnit from "jss-plugin-default-unit";

// Override default units for specific properties
const plugin = defaultUnit({
  'min-width': 'pc',              // Use 'pc' instead of default 'px'
  'max-width': (val) => `${val}em`, // Custom function for unit conversion
  'line-height': ''               // No unit (unitless)
});

const jss = create().use(plugin);

Unit Constants

Named exports providing access to the default unit values used internally by the plugin.

/**
 * Pixel unit constant - uses CSS.px when available, otherwise 'px'
 */
export const px: string | CSSUnitValue;

/**
 * Millisecond unit constant - uses CSS.ms when available, otherwise 'ms'  
 */
export const ms: string | CSSUnitValue;

/**
 * Percent unit constant - uses CSS.percent when available, otherwise '%'
 */
export const percent: string | CSSUnitValue;

Advanced usage:

import defaultUnit, { px, ms, percent } from "jss-plugin-default-unit";

// Access the unit constants directly (mainly for internal use)
console.log(px);      // 'px' or CSS.px
console.log(ms);      // 'ms' or CSS.ms  
console.log(percent); // '%' or CSS.percent

// These constants adapt based on CSS Typed OM support
// In browsers with CSS Typed OM: CSS.px, CSS.ms, CSS.percent
// In other browsers: 'px', 'ms', '%'

Default Units Mapping

The plugin includes comprehensive default unit mappings for CSS properties:

  • px units: Layout properties (width, height, margin, padding, border, position, font-size, etc.)
  • ms units: Time-based properties (animation-duration, transition-duration, animation-delay, etc.)
  • % units: Transform origin properties (transform-origin, perspective-origin)

Supported property categories:

  • Animation properties (delay, duration)
  • Background properties (position, size)
  • Border properties (width, radius)
  • Margin and padding properties
  • Width and height properties
  • Position properties (top, left, bottom, right, inset)
  • Shadow properties (box-shadow, text-shadow)
  • Font and text properties
  • Grid and flexbox properties
  • Transform and perspective properties

Plugin Methods

onProcessStyle

Processes entire style objects during rule creation, applying units to all numeric values.

/**
 * Processes style object and adds units to numeric values
 * @param style - Style object to process
 * @param rule - JSS rule object
 * @returns Processed style object with units added
 */
onProcessStyle(style: Object, rule: Rule): Object;

onChangeValue

Processes individual property values when they change dynamically.

/**
 * Processes individual property values for unit addition
 * @param value - The property value to process
 * @param prop - The CSS property name
 * @returns Processed value with unit added if applicable
 */
onChangeValue(value: any, prop: string): any;

Advanced Features

Property Name Conversion

The plugin supports both kebab-case and camelCase CSS property names:

const styles = {
  fontSize: 16,           // Works with camelCase
  'font-size': 16,        // Works with kebab-case
  borderRadius: 4,        // camelCase
  'border-radius': 4      // kebab-case
};

Nested Objects and Arrays

Handles complex style structures with nested objects and arrays:

const styles = {
  // Nested objects (like media queries)
  '@media (min-width: 768px)': {
    width: 500,     // becomes "500px"
    height: 300     // becomes "300px"
  },
  
  // Arrays for multiple values
  boxShadow: [
    [0, 2, 4, 'rgba(0,0,0,0.1)'],  // 0px, 2px, 4px
    [0, 8, 16, 'rgba(0,0,0,0.2)']  // 0px, 8px, 16px
  ],
  
  // Fallback values
  fallbacks: {
    width: 400,     // becomes "400px"
    width: 500      // becomes "500px"
  }
};

Zero Value Handling

Special handling for zero values to avoid unnecessary "0px":

const styles = {
  margin: 0,          // Stays as 0 (not "0px")
  padding: 10,        // becomes "10px"
  borderWidth: 0      // Stays as 0 (not "0px")
};

CSS Typed OM Integration

When available, the plugin uses CSS Typed OM for better performance:

// In browsers with CSS Typed OM support:
// px = CSS.px, ms = CSS.ms, percent = CSS.percent

// In other browsers:
// px = 'px', ms = 'ms', percent = '%'

Error Handling

The plugin gracefully handles various input types:

  • null/undefined values: Passed through unchanged
  • Non-numeric values: Passed through unchanged
  • String values: Passed through unchanged
  • NaN values: Passed through unchanged
  • Object/Array values: Recursively processed

Integration with Other JSS Plugins

Compatible with other JSS plugins:

import { create } from "jss";
import defaultUnit from "jss-plugin-default-unit";
import expand from "jss-plugin-expand";
import nested from "jss-plugin-nested";

const jss = create().use(
  nested(),
  expand(),
  defaultUnit()  // Should typically be last in the chain
);

TypeScript Support

Full TypeScript support with type definitions:

import defaultUnit from "jss-plugin-default-unit";
import { Plugin } from "jss";

// Basic usage with string units
const options = {
  'custom-property': 'rem'
};

const plugin: Plugin = defaultUnit(options);

Note: The TypeScript definitions currently only support string values in options, but the runtime also supports function transformers as shown in the JavaScript examples above.