React Server side rendering of CSS modules

可紊 提交于 2019-12-12 07:09:41

问题


The current practice for CSS with React components seems to be using webpack's style-loader to load it into the page in.

import React, { Component } from 'react';
import style from './style.css';

class MyComponent extends Component {
    render(){
        return (
            <div className={style.demo}>Hello world!</div>
        );
    }
}

By doing this the style-loader will inject a <style> element into the DOM. However, the <style> will not be in the virtual DOM and so if doing server side rendering, the <style> will be omitted. This cause the page to have FOUC.

Is there any other methods to load CSS modules that work on both server and client side?


回答1:


You can have a look at the isomorphic-style-loader. The loader was specifically created to solve this kind of issues.

However for using this you have to use an _insertCss() method provided by the loader. The documentation details how to use it.

Hope it helped.




回答2:


You can use webpack/extract-text-webpack-plugin. This will create a independently redistributable stylesheet you can reference then from your documents.




回答3:


For me, I am using the Webpack loader css-loader to implement CSS modules in isomorphic application.

On server side, the webpack config will be like this:

  module: {
    rules: [
      {
        test: /\.(css)$/,
        include: [
          path.resolve(__dirname, '../src'),
        ],
        use: [
          {
            // Interprets `@import` and `url()` like `import/require()` and will resolve them
            loader: 'css-loader/locals',
            options: {
              modules: true,
              localIdentName: '[name]__[local]--[hash:base64:5]'
            }
          },
        ],
      },
    ]
  }

On client side, the webpack config looks like this

          {
            // Interprets `@import` and `url()` like `import/require()` and will resolve them
            loader: 'css-loader',
            options: {
              modules: true,
              localIdentName: '[name]__[local]--[hash:base64:5]'
            }
          },

Off course, if you are using SASS, you need to use sass-loader to compile scss to css, and postcss-loader can help to add the autoprefixer.



来源:https://stackoverflow.com/questions/34615898/react-server-side-rendering-of-css-modules

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!