Skip to content

引入样式

全局样式

css
/* src/assets/global.css */
button {
  background-color: rgb(48, 177, 220);
  height: 30px;
  width: 100px;
}

button:hover {
  background-color: lightblue;
}

引入

js
// server/App.jsx
import "./assets/global.css";

组件样式

css
/* src/pages/Home/index.css */
.button-font {
  color: red;
  font-size: 18px;
}

body {
  background-color: #f5f5f5;
}

引入

js
// src/pages/Home/index.jsx
import React, { useState } from "react";
import style from "./index.css";

export default function () {
  const [count, setCount] = useState(0);
  const handleClick = (e) => {
    // console.log(e);
    setCount(count + 1);
  };
  return (
    <>
      <h1>Hello World</h1>
      <h3>第一个React SSR Demo</h3>
      <h3>点击操作:{count}</h3>
      <button className={styles["button-font"]} onClick={handleClick}>
        点击
      </button>
    </>
  );
}

webpack 生成文件

安装相关依赖

  • css-loader:用于解析 CSS 文件并生成对应的 JS 代码
  • mini-css-extract-plugin:用于将 CSS 提取到单独的文件中,而不是内联到 JavaScript 中。
  • isomorphic-style-loader:用于在服务器和客户端之间共享样式。
bash
yarn add css-loader@^3.4.2 -D
yarn add isomorphic-style-loader@^5.4.0 -D
yarn add mini-css-extract-plugin@^2.9.2 -D

利用client 生成文件

js
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
  // ...
  plugins: [
    // ...
    new MiniCssExtractPlugin({
      filename: "css/bundle.[hash:5].css",
    }),
  ],
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, "css-loader?modules"], // 添加 modules
      },
    ],
  },
};
  • new MiniCssExtractPlugin(): 创建一个插件实例,用于将 CSS 提取到单独的文件(./public/css/bundle.[hash:5].css)中。
  • MiniCssExtractPlugin.loader: 将 MiniCssExtractPlugin 的 loader 添加到 webpack 的 loader 链中。
  • "css-loader?modules": 将 CSS 模块化处理,并使用 css-loader 来解析 CSS 文件。

利用server 生成文件

js
module.exports = {
  //...
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ["isomorphic-style-loader", "css-loader?modules"],
      },
    ],
  },
};
  • "isomorphic-style-loader": 用于在服务器端渲染时,将 CSS 样式注入到 HTML 中。
  • "css-loader?modules": 将 CSS 模块化处理,并使用 css-loader 来解析 CSS 文件。

动态引入样式文件

utils.js

js
// server/utils.js
export function getCssFileName(dirPath = "./public/css") {
  return fs
    .readdirSync(dirPath)
    .filter((file) => file.endsWith(".css"))
    .map((file) => {
      return `<link rel="stylesheet" href="./css/${file}">`;
    });
}

render.js

js
// server/render.js
import { getFileName, getCssFileName } from "./utils";

export default (req, res) => {
  const componentHTML = ReactDom.renderToString(<App />);
  const html = `
  <!DOCTYPE html>
  <html lang="en">
  <head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>SSR</title>
    ${getCssFileName()}
  </head>
  <body>
    <div id="root">${componentHTML}</div>
    ${getFileName()}
    </body>
  </html>
  `;
  res.send(html);
};

Released under the MIT License.