Installation
1. Install the latest version with yarn:
yarn add color-shorthand-hex-to-six-digit
or with npm:
npm install color-shorthand-hex-to-six-digit
2. Import it in your code:
import { conv, version } from "color-shorthand-hex-to-six-digit";
Quick Take
import { strict as assert } from "assert";
import { conv } from "color-shorthand-hex-to-six-digit";
// converts shorthand hex color codes within strings (imagine that could be
// email template source code):
assert.equal(
conv("aaaa #f0c zzzz\n\t\t\t#fc0"),
"aaaa #ff00cc zzzz\n\t\t\t#ffcc00"
);
// converts shorthand hex colour codes within plain objects:
assert.deepEqual(
conv({
a: "#ffcc00",
b: "#f0c",
c: "text",
}),
{
a: "#ffcc00",
b: "#ff00cc",
c: "text",
}
);
// converts shorthand hex colour codes within arrays:
assert.deepEqual(conv(["#fc0", "#f0c", "text", ""]), [
"#ffcc00",
"#ff00cc",
"text",
"",
]);
// converts shorthand hex colour codes within nested spaghetti's:
assert.deepEqual(
conv([[[[[[{ x: ["#fc0"] }]]]]], { z: "#f0c" }, ["text"], { y: "" }]),
[[[[[[{ x: ["#ffcc00"] }]]]]], { z: "#ff00cc" }, ["text"], { y: "" }]
);
// in all other cases it silently returns the input:
assert.equal(conv(null), null);
Purpose
It’s a best practice to avoid shorthand color codes in email, for example, <td bgcolor='#ccc'>
. This program converts three-digit hex color codes inside any data structures (strings, objects or arrays), for example <td bgcolor='#cccccc'>
.
API — conv()
The main function conv()
is imported like this:
import { conv } from "color-shorthand-hex-to-six-digit";
It’s a function which takes one input argument:
function conv (input: any): any;
- If the input is string, a converted string will be returned.
- If input is array or a plain object, it will be traversed and any hex codes within strings inside will be converted.
- If input is unsuitable: falsy things, functions etc. — input will be returned as is.
This program never throws an error, it’s meant to be used as a by-pass function.
Usage in Gulp environment
You don’t need a Gulp plugin; you can simply use this library whenever you get in control of the final stream, or especially, SCSS variables.
For example, tap the color-shorthand-hex-to-six-digit
right after importing the SCSS variables. We hope you are not misbehaving and all your colour variables are in one place only, as variables.
// import SCSS variables from file (modules/src/scss/_variables.scss)
// native Node function to help with paths:
import path from "path";
// convert variables SCSS file to .JSON:
import scssToJson from "scss-to-json";
// lodash:
import mapKeys from "lodash.mapKeys";
// ...
function getScssVars() {
const sassFilePath = path.resolve(
__dirname,
"modules/src/scss/_variables.scss"
);
const tempSassVars = scssToJson(sassFilePath);
sassVars = mapKeys(tempSassVars, function (value, key) {
return key.slice(1);
});
// convert all bad hex codes:
sassVars = convShorthand(sassVars);
// console.log('sassVars = ' + JSON.stringify(sassVars, null, 4))
}