Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS-Module classes are undefined while React server side rendering

I am not using Webpack config for React SSR. Instead this is my config:

require("@babel/register")({
  presets: ["@babel/preset-env", "@babel/preset-flow", "@babel/preset-react"],
  plugins: [
    "@babel/plugin-transform-runtime",
    "@babel/plugin-proposal-class-properties",
    "babel-plugin-dynamic-import-node",
    "@babel/plugin-transform-modules-commonjs",    
    [
      "module-resolver",
      {
        root: ["./src"]
      }
    ]
  ]
});

require("ignore-styles");

module.exports = require("./server.js");

The problem is css classes are undefined in the rendered html. How can I fix this?

like image 556
Hadi Ranjbar Avatar asked Jan 08 '20 09:01

Hadi Ranjbar


1 Answers

I finally added this plugin to babel:

[
  "css-modules-transform",
  {
    camelCase: true,
    extensions: [".css", ".scss"],
    preprocessCss: "./ssr/utils/SsrCssModuleHandler.js",
    generateScopedName: "[hash:base64:5]"
  }
]

in which SsrCssModuleHandler is a module:

    var sass = require('node-sass');

    var path = require('path');

    module.exports = function processSass(data, filename) {
        var result;
        result = sass.renderSync({
            data: data,
            file: filename
        }).css;
        return result.toString('utf8');
    };

and the problem is solved!

like image 77
Hadi Ranjbar Avatar answered Oct 28 '22 17:10

Hadi Ranjbar