or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

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

0

# JSS Plugin Default Unit

1

2

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.

3

4

## Package Information

5

6

- **Package Name**: jss-plugin-default-unit

7

- **Package Type**: npm

8

- **Language**: JavaScript with TypeScript definitions

9

- **Installation**: `npm install jss-plugin-default-unit`

10

11

## Core Imports

12

13

```javascript

14

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

15

```

16

17

For CommonJS:

18

19

```javascript

20

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

21

```

22

23

24

## Basic Usage

25

26

```javascript

27

import { create } from "jss";

28

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

29

30

// Create JSS instance with default unit plugin

31

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

32

33

// Create styles with numeric values - units are added automatically

34

const sheet = jss.createStyleSheet({

35

button: {

36

width: 100, // becomes "100px"

37

height: 50, // becomes "50px"

38

margin: 10, // becomes "10px"

39

borderRadius: 5, // becomes "5px"

40

animationDuration: 300 // becomes "300ms"

41

}

42

});

43

```

44

45

## Architecture

46

47

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

48

49

- **onProcessStyle**: Processes entire style objects during rule creation, recursively applying units to numeric values

50

- **onChangeValue**: Handles individual property value changes during dynamic updates

51

52

**Core Components:**

53

54

- **Unit Mapping System**: Comprehensive mapping of 170+ CSS properties to their default units (px, ms, %)

55

- **Property Name Normalization**: Supports both kebab-case and camelCase CSS property names through automatic conversion

56

- **Recursive Processing**: Handles nested objects (media queries, fallbacks) and arrays (multiple values)

57

- **CSS Typed OM Integration**: Uses CSS Typed OM when available for improved performance, falls back to string units

58

59

**Processing Flow:**

60

1. User provides numeric values in style objects

61

2. Plugin identifies the CSS property name (normalizing case)

62

3. Looks up default unit from internal mapping or custom options

63

4. Applies unit to numeric values (with special handling for zero values)

64

5. Recursively processes nested structures

65

66

## Capabilities

67

68

### Plugin Factory Function

69

70

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

71

72

```javascript { .api }

73

/**

74

* Creates a JSS plugin that adds default units to numeric values

75

* @param options - Optional configuration for custom unit overrides

76

* @returns JSS Plugin object with onProcessStyle and onChangeValue methods

77

*/

78

function defaultUnit(options?: Options): Plugin;

79

80

interface Options {

81

[propertyName: string]: string | ((value: number) => string);

82

}

83

84

interface Plugin {

85

onProcessStyle(style: Object, rule: Rule): Object;

86

onChangeValue(value: any, prop: string): any;

87

}

88

```

89

90

**Usage with custom options:**

91

92

```javascript

93

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

94

95

// Override default units for specific properties

96

const plugin = defaultUnit({

97

'min-width': 'pc', // Use 'pc' instead of default 'px'

98

'max-width': (val) => `${val}em`, // Custom function for unit conversion

99

'line-height': '' // No unit (unitless)

100

});

101

102

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

103

```

104

105

### Unit Constants

106

107

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

108

109

```javascript { .api }

110

/**

111

* Pixel unit constant - uses CSS.px when available, otherwise 'px'

112

*/

113

export const px: string | CSSUnitValue;

114

115

/**

116

* Millisecond unit constant - uses CSS.ms when available, otherwise 'ms'

117

*/

118

export const ms: string | CSSUnitValue;

119

120

/**

121

* Percent unit constant - uses CSS.percent when available, otherwise '%'

122

*/

123

export const percent: string | CSSUnitValue;

124

```

125

126

**Advanced usage:**

127

128

```javascript

129

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

130

131

// Access the unit constants directly (mainly for internal use)

132

console.log(px); // 'px' or CSS.px

133

console.log(ms); // 'ms' or CSS.ms

134

console.log(percent); // '%' or CSS.percent

135

136

// These constants adapt based on CSS Typed OM support

137

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

138

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

139

```

140

141

### Default Units Mapping

142

143

The plugin includes comprehensive default unit mappings for CSS properties:

144

145

- **px units**: Layout properties (width, height, margin, padding, border, position, font-size, etc.)

146

- **ms units**: Time-based properties (animation-duration, transition-duration, animation-delay, etc.)

147

- **% units**: Transform origin properties (transform-origin, perspective-origin)

148

149

**Supported property categories:**

150

- Animation properties (delay, duration)

151

- Background properties (position, size)

152

- Border properties (width, radius)

153

- Margin and padding properties

154

- Width and height properties

155

- Position properties (top, left, bottom, right, inset)

156

- Shadow properties (box-shadow, text-shadow)

157

- Font and text properties

158

- Grid and flexbox properties

159

- Transform and perspective properties

160

161

### Plugin Methods

162

163

#### onProcessStyle

164

165

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

166

167

```javascript { .api }

168

/**

169

* Processes style object and adds units to numeric values

170

* @param style - Style object to process

171

* @param rule - JSS rule object

172

* @returns Processed style object with units added

173

*/

174

onProcessStyle(style: Object, rule: Rule): Object;

175

```

176

177

#### onChangeValue

178

179

Processes individual property values when they change dynamically.

180

181

```javascript { .api }

182

/**

183

* Processes individual property values for unit addition

184

* @param value - The property value to process

185

* @param prop - The CSS property name

186

* @returns Processed value with unit added if applicable

187

*/

188

onChangeValue(value: any, prop: string): any;

189

```

190

191

## Advanced Features

192

193

### Property Name Conversion

194

195

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

196

197

```javascript

198

const styles = {

199

fontSize: 16, // Works with camelCase

200

'font-size': 16, // Works with kebab-case

201

borderRadius: 4, // camelCase

202

'border-radius': 4 // kebab-case

203

};

204

```

205

206

### Nested Objects and Arrays

207

208

Handles complex style structures with nested objects and arrays:

209

210

```javascript

211

const styles = {

212

// Nested objects (like media queries)

213

'@media (min-width: 768px)': {

214

width: 500, // becomes "500px"

215

height: 300 // becomes "300px"

216

},

217

218

// Arrays for multiple values

219

boxShadow: [

220

[0, 2, 4, 'rgba(0,0,0,0.1)'], // 0px, 2px, 4px

221

[0, 8, 16, 'rgba(0,0,0,0.2)'] // 0px, 8px, 16px

222

],

223

224

// Fallback values

225

fallbacks: {

226

width: 400, // becomes "400px"

227

width: 500 // becomes "500px"

228

}

229

};

230

```

231

232

### Zero Value Handling

233

234

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

235

236

```javascript

237

const styles = {

238

margin: 0, // Stays as 0 (not "0px")

239

padding: 10, // becomes "10px"

240

borderWidth: 0 // Stays as 0 (not "0px")

241

};

242

```

243

244

### CSS Typed OM Integration

245

246

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

247

248

```javascript

249

// In browsers with CSS Typed OM support:

250

// px = CSS.px, ms = CSS.ms, percent = CSS.percent

251

252

// In other browsers:

253

// px = 'px', ms = 'ms', percent = '%'

254

```

255

256

## Error Handling

257

258

The plugin gracefully handles various input types:

259

260

- **null/undefined values**: Passed through unchanged

261

- **Non-numeric values**: Passed through unchanged

262

- **String values**: Passed through unchanged

263

- **NaN values**: Passed through unchanged

264

- **Object/Array values**: Recursively processed

265

266

## Integration with Other JSS Plugins

267

268

Compatible with other JSS plugins:

269

270

```javascript

271

import { create } from "jss";

272

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

273

import expand from "jss-plugin-expand";

274

import nested from "jss-plugin-nested";

275

276

const jss = create().use(

277

nested(),

278

expand(),

279

defaultUnit() // Should typically be last in the chain

280

);

281

```

282

283

## TypeScript Support

284

285

Full TypeScript support with type definitions:

286

287

```typescript

288

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

289

import { Plugin } from "jss";

290

291

// Basic usage with string units

292

const options = {

293

'custom-property': 'rem'

294

};

295

296

const plugin: Plugin = defaultUnit(options);

297

```

298

299

**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.