Import JavaScript file which exports styled.css
Some how CSS post processing are little complicated, and do not provide best editing experience and we cannot debug what is being generated.
- We get intellisense with VS code extension for pure CSS properties, color editor etc.
- We can utilize JavaScript's rich language features to generate output the way we want.
- We can debug JavaScript to see what is being generated, typical PostCSS or any CSS Processor does not support debugging.
- `npm install -D postcss-import-styled-js
- 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")()
]
});
main.css
/** This will import JS files */
@import-styled-js "./**/*.css.js";
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;
}
}
postcss-import-styled-js
will compile all .css.js
files to .css
file and import the generated file in the target main css file.