programing

CSS 모듈의 리액트 서버 측 렌더링

lastcode 2023. 2. 13. 20:33
반응형

CSS 모듈의 리액트 서버 측 렌더링

현재 CSS with React 컴포넌트의 프랙티스는 웹 팩의 스타일 로더를 사용하여 페이지에 로드하는 것으로 보입니다.

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

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

이렇게 함으로써 스타일 로더는 1차적으로<style>요소를 DOM에 추가합니다.하지만, 그<style>가상 DOM에 존재하지 않기 때문에 서버 측 렌더링을 실행하면<style>생략됩니다.이것에 의해, 페이지에 FOC 가 표시됩니다.

서버와 클라이언트 양쪽에서 동작하는 CSS 모듈을 로드하는 다른 방법이 있습니까?

를 사용할 수 있습니다.그러면 문서에서 참조할 수 있는 독립적으로 재배포 가능한 스타일시트가 생성됩니다.

이형식 로더를 보실 수 있습니다.로더는 이러한 문제를 해결하기 위해 특별히 제작되었습니다.

단, 이 기능을 사용하려면_insertCss()로더에 의해 제공되는 메서드.사용 방법에 대해서는, 메뉴얼에 상술되어 있습니다.

도움이 됐으면 좋겠다.

저는 Webpack loader css-loader를 사용하여 CSS 모듈을 동형 어플리케이션으로 구현하고 있습니다.

서버측에서는, Web pack 의 설정은 다음과 같습니다.

  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]'
            }
          },
        ],
      },
    ]
  }

클라이언트 측에서는 웹 팩 설정은 다음과 같습니다.

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

물론 SAS를 사용하고 있다면sass-loaderscs를 css로 컴파일하다postcss-loader추가에 도움이 될 수 있습니다.autoprefixer.

언급URL : https://stackoverflow.com/questions/34615898/react-server-side-rendering-of-css-modules

반응형