CSS-Module classes are undefined while React server side rendering

1.8k Views Asked by At

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?

2

There are 2 best solutions below

0
Hadi Ranjbar On BEST ANSWER

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!

0
David Bradshaw On

The above config is for Babel which is only going to process JS. If you want to use CSS-modules without webpack, then you still need to process your CSS into a format that works in the bowsers.

The best css processor is called PostCSS and their is a plug-in for CSS-Module support

https://github.com/css-modules/postcss-modules