Write stylesheets in JS.
Works with any stack.
npm install [--save] jss-lite-loader
jss-lite-loader is very flexible. Feel free to combine it with other loaders – for example, style-loader for adding the styles to the page or apply-loader for configurable stylesheets.
You can use it like a good old CSS preprocessor like LESS or SASS:
∎ config.js
const color = require('color');
exports.buttonBackground =
color('#F44336').alpha(0.5).lighten(0.5).rgbaColor();
∎ style.js
const { buttonBackground } = require('./config');
exports.stylesheet = {
'.button': {
'width': '50px',
'background-color': buttonBackground,
},
'@media screen and (min-width: 80em)': {
'.button': {
'width': '100%',
},
},
};
∎ index.js
require('style!jss-lite!./style');
Here’s a problem I encountered recently, which turned out to be a perfect match for jss-lite-loader. I use a bunch of brand-specific colors in my jss-lite stylesheets:
∎ header.js
const colors = require('material-colors');
const headerColor = exports.headerColor =
materialColors.grey[800];
exports.stylesheet = {
'.header': {
'height': '60px',
'background-color': headerColor,
},
};
And here’s the wow. I can use the same values in JS for things CSS can’t do. For example, setting the theme-color
:
∎ index.js
const h = require('hyperscript');
// This gets rendered and injected as CSS:
require('style!jss-lite!./header');
// The same file can be imported as a pure JS module, free of side effects:
const { headerColor } = require('./header');
document.head.appendChild(
h('meta', { name: 'theme-color', content: headerColor })
);
Until now sharing variables between JS and CSS was notoriously difficult.
Because the API is so simple, you can add lots of features yourself. Here’s an example of unique, auto-generated class names and a configurable stylesheet function (for example, coming from a style framework) in a reusable hyperscript component. Whoah, that’s a lot at once!
∎ style.js
const hash = require('hash-sum')(__filename);
const classes = {
button = `${hash}-button`,
};
module.exports = ({
backgroundColor,
}) => ({ stylesheet: {
[`.${classes.button}`]: {
'width': '50px',
'background-color': indigo,
},
'@media screen and (min-width: 80em)': {
[`.${classes.button}`]: {
'width': '100%',
},
},
} });
Object.assign(module.exports, { classes });
∎ button.js
require('style!jss-lite!apply?{ obj: { backgroundColor: "#F44336" } }!./style');
const { classes } = require('./style');
export default () => (
h(`button.${classes.button}`)
);