[英]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.