Skip to content

mbrandau/css-shortener

Folders and files

NameName
Last commit message
Last commit date
Mar 26, 2022
Mar 26, 2022
Mar 26, 2022
Mar 26, 2022
Mar 26, 2022
Mar 26, 2022
Mar 26, 2022
Mar 24, 2022
Mar 26, 2022
May 18, 2022
Mar 27, 2022
Mar 24, 2022
May 18, 2022

Repository files navigation

css-shortener

CI npm npm GitHub issues

Preview

/* BEFORE */
p.this-class-is-extremely-long-and-definitely-needs-to-be-shortened,
p.why-is-this-so-long-if-it-just-makes-white-text {
  color: white;
}

/* AFTER */
p.a,
p.b {
  color: white;
}

Table of contents

  1. Quick Start
  2. API Documentation
    1. Constructor
    2. #importMap(map, override)
    3. #map
  3. Examples
    1. CSS filter for nunjucks and express

Quick Start

import { CssShortener } from 'css-shortener';

const shortener = new CssShortener();

console.log(shortener.shortenClassName('long-class'));
// Output: a

console.log(shortener.map);
// Output: {
//   "long-class": "a"
// }

API Documentation

Constructor

const options = {
  alphabet: 'abcdef',
};
const shortener = new CssShortener(options);

The options parameter can be omitted.

Options

Option Type Optionality Description Default value
alphabet string optional The alphabet is used to generate the new class names. 'abcefghijklmnopqrstuvwxyz0123456789_-'

Note that there is no d in the default alphabet to avoid generation of the combination ad.

#importMap(map, override)

Imports mappings into the shortener

cssShortener.importMap(
  {
    'my-extremely-long-class-name': 'a',
  },
  false
);

If override is true, class names that are already mapped will be overridden.
The override parameter can be omitted.

#map

Returns the mapped class names

var map = cssShortener.getMap();
{
  "my-extremely-long-class-name": "a"
}

Examples

CSS filter for nunjucks and express

const express = require('express');
const nunjucks = require('nunjucks');

const cssMap = JSON.parse(fs.readFileSync('./cssMap.json'));

const app = express();
const env = nunjucks.configure('your-views-folder', { express: app });

env.addFilter('css', function(str) {
  return str
    .split(' ')
    .map(c => (cssMap[c] != null ? cssMap[c] : c))
    .join(' ');
});
<!-- BEFORE -->
<div class="{{'my-extremely-long-class-name'|css}}"></div>
<!-- RENDERED -->
<div class="a"></div>