Create plugin to handle json design tokens
This commit is contained in:
parent
acc355fd09
commit
d6b64ff062
41
_config/eleventy-plugin-tokens.js
Normal file
41
_config/eleventy-plugin-tokens.js
Normal file
|
|
@ -0,0 +1,41 @@
|
||||||
|
/**
|
||||||
|
* Inspired by CSS { In Real Life }'s blog post
|
||||||
|
* https://css-irl.info/creating-css-variables-from-a-js-file/
|
||||||
|
*/
|
||||||
|
import fs from 'fs';
|
||||||
|
import { writeFile } from 'fs/promises';
|
||||||
|
|
||||||
|
let config = {}
|
||||||
|
export default function (eleventyConfig, pluginOptions) {
|
||||||
|
config = pluginOptions;
|
||||||
|
|
||||||
|
eleventyConfig.on("eleventy.before", () => {
|
||||||
|
let theme = fs.readFileSync(`./${config.tokens || 'src/_data/tokens.json'}`, 'utf-8');
|
||||||
|
buildTheme(JSON.parse(theme))
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const mapTheme = ([key, value]) => {
|
||||||
|
if (typeof value === 'string') {
|
||||||
|
return `--${key}: ${value}`
|
||||||
|
}
|
||||||
|
|
||||||
|
return Object.entries(value).flatMap(([nestedKey, nestedValue]) => {
|
||||||
|
const newKey = nestedKey === 'DEFAULT' ? key : `${key}-${nestedKey}`
|
||||||
|
|
||||||
|
return mapTheme([newKey, nestedValue])
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const buildTheme = async (theme) => {
|
||||||
|
try {
|
||||||
|
const result = Object.entries(theme).flatMap(mapTheme)
|
||||||
|
|
||||||
|
let content = result.map((line) => `\t${line};`)
|
||||||
|
content = [':root {', ...content, '}'].join('\n')
|
||||||
|
|
||||||
|
await writeFile(`./${config.destination || 'src/css/theme.css'}`, content, { encoding: 'utf-8' })
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
import { inspect } from "util";
|
import { inspect } from "util";
|
||||||
import pluginIcons from 'eleventy-plugin-icons';
|
import pluginIcons from 'eleventy-plugin-icons';
|
||||||
import eleventyPDF from "./_config/eleventy-plugin-pdf.js";
|
import eleventyPDF from "./_config/eleventy-plugin-pdf.js";
|
||||||
|
import pluginTokens from "./_config/eleventy-plugin-tokens.js";
|
||||||
|
|
||||||
export default async function (eleventyConfig) {
|
export default async function (eleventyConfig) {
|
||||||
eleventyConfig.setUseGitIgnore(false);
|
eleventyConfig.setUseGitIgnore(false);
|
||||||
|
|
@ -28,6 +29,7 @@ export default async function (eleventyConfig) {
|
||||||
|
|
||||||
eleventyConfig.addPassthroughCopy('src/favicon.ico')
|
eleventyConfig.addPassthroughCopy('src/favicon.ico')
|
||||||
|
|
||||||
|
eleventyConfig.addPlugin(pluginTokens, { tokens: "./src/_data/tokens.json", destination: "./src/css/theme.css" });
|
||||||
eleventyConfig.addPlugin(eleventyPDF);
|
eleventyConfig.addPlugin(eleventyPDF);
|
||||||
eleventyConfig.addPlugin(pluginIcons, {
|
eleventyConfig.addPlugin(pluginIcons, {
|
||||||
sources: [
|
sources: [
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue