Structured way to write CSS in JS file.
Usage
Install the package:
$ npm install injected-css
Add injected-css/babel
to plugins section in your babel config:
Define real CSS in your JS file using css{}
template expression,
and refer to resulted classes using style
object.
const style = css` text-align: center; &-button { background-color: ; width: 32rem; padding: 2rem; border-radius: 0.5rem; border: none; &:hover { background-color: ; } @media { width: 16rem; } }` documentinnerHTML = ` Click me! `
It transforms to:
;; const style = css; documentinnerHTML = ` Click me! `;
Benefits
- Write real CSS and use JS for import/export, variables and dynamic strings
- Use powerful tools of JS world
- ES modules to manage dependencies between styles and JS components
- Eslint to ensure, it's hard to write bad CSS
- Variables and functions
- Webpack 2, Hot Module Replacement, code splitting, and server side render
- Built-in naming convention for component world
- Postcss integration (100s of plugins and custom syntaxes like SASS)
- Minimal overhead (no parsing cost, 400 byte runtime)
Custom postcss config
Just create .postcssrc.js
file with content similar to (read more about postcss config):
module plugins: 'features': 'rem': false ctxenv === 'production' ? autoprefixer: false : false
Inject global styles
Use inject()
method to insert global css
string.
Everything tagged literal with css`` will be preparsed with postcss.
; // insert regular css, like normalize.css // setup global typography
Server side render
Use flush()
method to get all css calls.
const body = const css = reset_css + const html = ` <!doctype html> <html lang='en-US'> <head> <title>My App</title> <style></style> </head> <body> </body> </html>` const reset =
Syntax highlight
Atom with language-babel plugin supports syntax highlight and autocompletion by default.
Credits
- BEM and SUIT CSS - for name convention, that works
- CSS modules - for embracing CSS syntax and adding the way to reference on classes from JS code
- style-loader - for concept of loading styles with js
- styled-jsx - for idea of babel plugin and this credits section
- @rtsao - for his open-source work on many css-in-js libraries
- styling - for embracing ES modules to export CSS
- react - for component approach and development philosophy
- CSS: The Definitive Guide - for explaining me details of CSS
- styled-components - for showing how to highlight CSS in tagged template literal