11ty-resume/_config/eleventy-plugin-tokens.js

41 lines
1.1 KiB
JavaScript

/**
* 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)
}
}