簡體   English   中英

如何在服務器端渲染ReactJs中將CSS文件轉換為HTML?

[英]How to get css file to html in server side rendering ReactJs?

我正在為我的React JS App執行服務器端渲染。但是我無法將.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文件。

在html文件中進行更改

    <link rel="stylesheet" type="text/css" href="styles.css">

您包含CSS的方式將不起作用。 假設您已將style.css文件放置在根目錄中名為Styles的文件夾中,並且在根目錄中具有服務器入口點index.js。

您必須首先將此目錄托管為靜態文件夾,方法是在index.js中添加以下行

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

托管后,您將可以訪問此目錄中的文件

您可以使用網址訪問文件

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

將此網址添加到您的HTML中

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM