egoist / egoist/rollup-plugin-postcss
Extract "css" variable in JS for custom Server Side Rendering
- Dominant language
- JavaScript
- Stars
- 689
- Forks
- 210
- PR merge metrics
- No merged PRs in 30d
Description
Hi,
We use css-modules in a react app. In our webpack based web app, in order to collect styles for the critical components, we basically wrap those components into a HOC. This decorator basically accumulates all the generated CSS and inlines it into the HTML while server side rendering.
Example;
```jsx
// component
import styles from "./styles.scss";
import { withStyles } from "utils/with-styles";
function Component (props) {
return
}
export default withStyles(Component, styles);
```
```jsx
// utils/with-styles.js
export function withStyles(Component, styles) {
const context = useContext(CriticalCSSContext);
if(context && context.addStyles) {
if (!context.criticalStyles.has(styles._getId) {
context.addStyles(styles._getId(), styles._getCss());
}
}
return (props) => ;
}
```
```jsx
// index.js
function App() {
const criticalStyles = useRef({});
const criticalCss = {
addStyles: (id, css) => {
criticalStyles[id].current = css
},
criticalStyles: {
has: (id) => criticalStyles.current[id],
},
};
return (
);
}
```
While we can access the className-generatedClassName map, we can't quite get the actual "css" content. To access the generated CSS, we wrote a custom style loader that exports the CSS content.
I was wondering if the same could be achieved by getting a onExport hook/plugin/loader where we can essentially add `module.exports.css = css;` line in the final css module file.
This is the style loader we wrote for webpack;
```js
// custom_webpack_style_loader.js
var stringifyRequest = require("loader-utils").stringifyRequest;
module.exports = function loader() {};
module.exports.pitch = function pitch(remainingRequest) {
if (this.cacheable) {
this.cacheable();
}
return `
var content = require(${stringifyRequest(this, `!!${remainingRequest}`)});
if (typeof content === 'string') {
content = [[module.id, content, '']];
}
module.exports = content.locals || {};
module.exports._getContent = () => content;
module.exports._getCss = () => content.toString();
module.exports._getId = () => module.id;
`;
};
```
I'm sorry if this is beyond the scope of this plugin, but would love some pointers to support this. Thank you so much for this wonderful plugin!
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.