Skip to content

ramasilveyra/templatize-css

Repository files navigation

Templatize CSS files

Do you want to generate dynamic CSS and you can't use CSS in JS?

Input

:root {
  --main-primary-color: brown; /* templatize-css: track */
  --main-mobile-primary-color: brown; /* templatize-css: track */
  --main-text-color: #fff; /* templatize-css: track */
  --main-link-color: #000;
}

.btn {
  background-color: var(--main-primary-color);
  color: var(--main-text-color);
  border: 0;
  padding: 10px 40px;
}

.btn-link {
  background-color: var(--main-link-color);
  border: 0;
  padding: 10px 40px;
}

@media (min-width: 992px) {
  .btn::after {
    background-color: var(--main-mobile-primary-color);
    padding: 5px 10px;
  }
}

Output

const defaults = {
  mainPrimaryColor: 'brown',
  mainMobilePrimaryColor: 'brown',
  mainTextColor: '#fff'
};

const templatize = locals => `.btn {
  background-color: ${locals.mainPrimaryColor || defaults.mainPrimaryColor};
  color: ${locals.mainTextColor || defaults.mainTextColor}
}
@media (min-width: 992px) {
  .btn::after {
    background-color: ${locals.mainMobilePrimaryColor || defaults.mainMobilePrimaryColor}
  }
}`;

module.exports = { defaults, templatize };

Table of Contents

Install

Node.js v8 or newer is required.

Via the yarn client:

$ yarn add --dev templatize-css

Via the npm client:

$ npm install --save-dev templatize-css

Usage

API

Compile

import { compile } from 'templatize-css';

const css = `:root {
  --main-bg-color: brown; /* templatize-css: track */
}

.btn {
  background-color: var(--main-bg-color);
}
`;

const template = compile(css);

Compile File

import path from 'path';
import { compileFile } from 'templatize-css';

const cssFilePath = path.resolve(__dirname, 'input.css');
const templateFilePath = path.resolve(__dirname, 'template.js');

compileFile(cssFilePath, templateFilePath).then(() => {
  console.log('File Compiled! 🍕');
});

CLI

Compile File (--out-file/-o)

templatize-css src/main.css --out-file src/template-main-css.js

Contribute

Feel free to dive in! Open an issue or submit PRs.

templatize-css follows the Contributor Covenant Code of Conduct.

License

MIT