A class name generator for css-loader with CSS Modules enabled.
Description
Save some extra bytes on your final bundle by shortening class names from something like [local]-[hash:base64:8]
down to a
... z
... A
... Z
... a0
... ZZ
etc.
This package provides class name generator factory with default alphabet of abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
. Produced generator function always starts out with single letter character from the beginning of the alphabet and keeps increasing it while at the same time guaranteeing the uniqueness of the class names.
Install
npm i css-loader-shorter-classnames -D
Basic usage
// Import class name generator factoryconst getLocalIdentName = ; // Create generatorconst getLocalIdent = ; // Supply created function as a loader options argument // ... loader: 'css-loader' options: modules: getLocalIdent
For css-loader
versions below 3.*
, modules
options should be specified in loader options
block instead:
const getLocalIdentName = ;const getLocalIdent = ; // Loader options // ... loader: 'css-loader' options: modules: true getLocalIdent
Enable only for production
const getLocalIdentName = ; const getLocalIdent = ;const isProduction = processenvNODE_ENV === 'production'; // Loader options // ... loader: 'css-loader' options: modules: localIdentName: '[local]-[hash:base64:8]' ...isProduction ? getLocalIdent : {}
Custom alphabet, prefix and suffix
Optionally supply a custom alphabet and/or prefix and/or suffix.
NB! Watch out for spaces and other invalid characters. It is guaranteed that none of the generated class names start with a number.
If you supply a prefix that starts with a number, it will be automatically prefixed with _
.
const classNameAlphabet getLocalIdentName = ; // Produces: 'a', 'b', 'c', 'aa', 'ba', ..., 'abcabca' etc.const getLocalIdent = ; // Produces: '_a', '_b', ..., '_aZ' etc.const getLocalIdent = ; // Produces: '_000a', '_000b', ..., '_000aZ' etc.const getLocalIdent = ; // Produces: '_a_', '_b_', ..., '_aZ_' etc.const getLocalIdent = ;
Usage with Vue CLI generated projects
vue.config.js
:
const getLocalIdentName = ; const getLocalIdent = ;const isProduction = processenvNODE_ENV === 'production'; moduleexports = // ... css: // ... loaderOptions: css: modules: localIdentName: '[local]-[hash:base64:8]' ...isProduction ? getLocalIdent : {} // ... // ...;