Minimum size unique CSS class names generator. It can be used with Webpack and Gatsby ecosystems. more
npm i mini-css-class-name
# or
yarn add mini-css-class-name
// CommonJS
const miniClassNames = require("mini-css-class-name");
// ES6
import miniClassName from "mini-css-class-name";
import miniClassNames from "mini-css-class-name";
const generate = miniClassNames({
prefix: "x__",
suffix: "--",
hash: 4,
});
generate(); // x__a--ZwkO
generate(); // x__b--9dO4
generate(); // x__c--rRI0
import miniClassNames from "mini-css-class-name";
const generate = miniClassNames();
generate(); // a
generate(); // b
generate(); // c
generate.reset();
generate(); // a
You can use a regular expression to exclude any characters.
const generate = miniClassName({ excludePattern: /[_-]/g }); // remove underscore and dash
const generateABC = miniClassName({ excludePattern: /[^a-z]/gi }); // keep only alphabet characters
webpack.config.js
// CommonJS
const getLocalIdent = require("mini-css-class-name/css-loader");
// ES6
import { getLocalIdent } from "mini-css-class-name";
There are two ways to plug it's depending on css-loader version.
css-loader >= 1.0.0 || >= 2.0.0
module.exports = {
// webpack config ...
module: {
rules: [
{
test: /\.css$/,
loader: "css-loader",
options: {
modules: true,
getLocalIdent: getLocalIdent(/* options */),
},
},
],
},
};
css-loader >= 3.0.0
module.exports = {
// webpack config ...
module: {
rules: [
{
test: /\.css$/,
loader: "css-loader",
options: {
modules: {
getLocalIdent: getLocalIdent(/* options */),
},
},
},
],
},
};
Documentation about css-modules
You also can use it with Gatsby v2
gatsby-node.js
const cloneDeepWith = require("lodash/cloneDeepWith");
const miniClassNames = require("mini-css-class-name/css-loader");
const generate = miniClassNames(/* options */);
exports.onCreateWebpackConfig = ({ stage, actions, getConfig }) => {
// For production builds state: 'build-javascript' and 'build-html'
if (stage.includes("build")) {
const config = getConfig();
config.module.rules = cloneDeepWith(config.module.rules, (value, key) => {
if (key === "options" && value.modules) {
return {
...value,
localIdentName: undefined,
getLocalIdent: generate,
};
}
});
actions.replaceWebpackConfig(config);
}
};
Name | Type | Default | Description |
---|---|---|---|
prefix | {String} |
"" |
A custom prefix will be added to each class name |
suffix | {String} |
"" |
A custom suffix will be added to each class name |
hash | {Number} |
0 |
A length of generating a random hash tail for each class name |
excludePattern | {RegExp} |
null |
A regular expression for removing characters |