Skip to content

PostCSS Plugin to import styled JavaScript files to dynamically generate CSS

License

Notifications You must be signed in to change notification settings

web-atoms/postcss-styled-js

Repository files navigation

PostCSS Styled JS

Import JavaScript file which exports styled.css

Why, Why, Why another tool?

Some how CSS post processing are little complicated, and do not provide best editing experience and we cannot debug what is being generated.

Benefits

  1. We get intellisense with VS code extension for pure CSS properties, color editor etc.
  2. We can utilize JavaScript's rich language features to generate output the way we want.
  3. We can debug JavaScript to see what is being generated, typical PostCSS or any CSS Processor does not support debugging.

Getting Started

Installation

  1. `npm install -D postcss-import-styled-js
  2. Add postcss-import-styled-js as a plugin
module.exports = (ctx) => ({
    map: { ... ctx.options.map, sourcesContent: false },
    plugins: [
        require("postcss-import-styled-js")(), // <-- this one
        require('postcss-preset-env')(),
        require("postcss-import")(),
        require("postcss-import-ext-glob")(),
        require("postcss-nested")(),
        require("cssnano")()
    ]
});

Examples

main.css

/** This will import JS files */
@import-styled-js "./**/*.css.js";

Sample CSS JS File

body.css.js

import styled from "postcss-import-styled-js";

const animations = Object.entries({
    div: "red",
    span: "blue"
}).map(([name, color]) =>
    styled.css `
        & ${name} {
            color: ${color};
        }
`);

export default styled.css `
    body {
        font-weight: 500;
        ${animations}
    }

`;

Above code will be transpiled as,

body {
    font-weight: 500;

    & div {
        color: red;
    }
    & span {
        color: blue;
    }
}

What is happening?

postcss-import-styled-js will compile all .css.js files to .css file and import the generated file in the target main css file.

About

PostCSS Plugin to import styled JavaScript files to dynamically generate CSS

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published