본문 바로가기
IT/react

[react] ssr 프로젝트 만들기 (2) - css, 번들에 추가하기

by 내일은교양왕 2024. 7. 2.

소스코드

https://github.com/insidedw/react-webpack5-ssr/commit/187a002c7787679afd3b390c158064d541293f14

 

inject css on csr · insidedw/react-webpack5-ssr@187a002

insidedw committed Jul 7, 2024

github.com

 

의존성 설치

npm i - D css-loader style-loader

 

설치 후 경고의 에러가 노출되었다.

npm WARN EBADENGINE Unsupported engine {
npm WARN EBADENGINE   package: 'css-loader@7.1.2',
npm WARN EBADENGINE   required: { node: '>= 18.12.0' },
npm WARN EBADENGINE   current: { node: 'v16.20.2', npm: '8.19.4' }
npm WARN EBADENGINE }
npm WARN EBADENGINE Unsupported engine {
npm WARN EBADENGINE   package: 'style-loader@4.0.0',
npm WARN EBADENGINE   required: { node: '>= 18.12.0' },
npm WARN EBADENGINE   current: { node: 'v16.20.2', npm: '8.19.4' }
npm WARN EBADENGINE }

 

원인은 사용하고 있는 노드 버전이 낮아 높게 설정해주었기 때문

버전을 올리고 패키지 내에서도 기본 노드버전을 세팅

 

노드버전 변경

(nvm, node 설치는 생략)

nvm ls
nvm use 20.11.1

 

package.json에 항목 추가

  "engines": {
    "node": ">=20.11.1"
  },

 

.nvmrc 파일 생성

20.11.1

 

다시 설치 후 확인해보면 의존성 버전이 올라가고 경고가 사라짐

 

webpack.client.js에 모듈 설치

css-loader: js에 import된 css파일을 해석

style-loader: 해석된 css를 html에 주입

const path = require('path')

module.exports = {
  mode: 'development',
  entry: './src/client.js',
  output: {
    path: path.resolve(__dirname, '../dist'),
    filename: 'client.bundle.js',
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
        },
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      },
    ],
  },
}

 

 

webpack.server.js

ssr할 때 번들링에 포함된 css 읽도록 설정

const path = require('path')
const nodeExternals = require('webpack-node-externals')

module.exports = {
  mode: 'development',
  entry: './src/server.js',
  target: 'node',
  externals: [nodeExternals()],
  output: {
    path: path.resolve(__dirname, '../dist'),
    filename: 'server.bundle.js',
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
        },
      },
      {
        test: /\.css$/,
        use: ['css-loader'],
      },
    ],
  },
}

 

 

App.css파일 추가

src/components/에 추가

h1 {
    color: dodgerblue;
}

 

App.js에 App.css 임포트

import React from 'react'
import './App.css'
const App = () => {
  return (
    <div>
      <h1>Hello, SSR!</h1>
    </div>
  )
}

export default App

 

테스트

npm run build
npm run start

 

localhost:3000

 

주의

ssr 시 css가 주입이 안되어 csr에 css가 주입되어 스타일이 변경되는걸 확인 할 수 있다.

추후 개선할 예정이다.