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;
// component
import styles from "./styles.scss";
import { withStyles } from "utils/with-styles";
function Component (props) {
return <div className={styles.wrapper}>{props.children}</div>;
}
export default withStyles(Component, styles);
// 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) => <Component {...props} />;
}
// index.js
function App() {
const criticalStyles = useRef({});
const criticalCss = {
addStyles: (id, css) => {
criticalStyles[id].current = css
},
criticalStyles: {
has: (id) => criticalStyles.current[id],
},
};
return (
<CriticalCSSContext.Provider value={criticalCss}>
<Root />
</CriticalCSSContext.Provider>
);
}
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;
// 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!
Pay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too