首页 > 解决方案 > 如何在服务器端渲染 ReactJs 中将 css 文件转换为 html?

问题描述

我正在为我的 React JS 应用程序进行服务器端渲染。但我无法将 .css 和图像加载到 html 文件中。

我的目录结构

build
public
 index.html
 styles.css
 fav.png
src
 client
  client.js
 index.js
webpack.js

我的 index.html 文件

<html>
<head>
  <title></title>
  <link rel="shortcut icon" href="%PUBLIC_URL%/fav.png">
  <link rel="stylesheet" type="text/css" href="./styles.css" />
</head>
<body>
 <div id="root"></div>
</body>
</html>

我的 index.js 文件(服务器文件)

import express from 'express';
import React from 'react';
import { renderToString } from 'react-dom/server';
import Home from './client/components/MyHome';
import path from 'path';
import fs from 'fs';
import Transmit from 'react-transmit';
import {createStore, applyMiddleware, compose} from 'redux';    
import reducers from './client/reducers';    
const store = createStore(reducers)

function handleRender(req, res) {
  Transmit.renderToString(Home).then(({reactString, reactData}) => {
    fs.readFile('./public/index.html', 'utf8', function (err, data) {

      const document = data.replace(/<div id="root"><\/div>/,
      `<div id="root">${reactString}</div>`);

      res.send(document);
    });
  });
}

const app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.get('*', handleRender);
app.listen(3000, () => {
    console.log('Listening on port 3000');
});

在 webpack.js 上加载 css

{
    test: /\.css$/,
    use: ExtractTextPlugin.extract(
     { fallback: 'style-loader', use: [ 'css-loader' ] }
   ) 
 }

问题是当我运行我的应用程序时,它没有加载 css 和 png 文件。

标签: node.jsreactjsexpressserver-side-rendering

解决方案


您包含 css 的方式将不起作用。假设您已将style.css文件放在根目录中名为Styles的文件夹中,并且在根目录中您有服务器入口点 index.js。

您必须首先将此目录托管为静态文件夹,这是通过在 index.js 中添加以下行来完成的

app.use("/Styles", express.static(path.join(__dirname, './Styles')));

这将允许您在托管后访问此目录中的文件

您可以使用 url 访问文件

 http://localhost:3000/Styles/styles.css

将此网址添加到您的 html

<link rel="stylesheet" type="text/css" href="http://localhost:3000/Styles/styles.css">

推荐阅读