[英]How to get css file to html in server side rendering ReactJs?
I'm doing server side rendering for my React JS App.But i cannot load .css and images to html file. 我正在为我的React JS App执行服务器端渲染。但是我无法将.css和图像加载到html文件中。
My directory structure 我的目录结构
build
public
index.html
styles.css
fav.png
src
client
client.js
index.js
webpack.js
my index.html file 我的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>
my index.js file (server file) 我的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');
});
load css on webpack.js 在webpack.js上加载CSS
{
test: /\.css$/,
use: ExtractTextPlugin.extract(
{ fallback: 'style-loader', use: [ 'css-loader' ] }
)
}
Problem is when i run my app,it's not loaded css and png files. 问题是当我运行我的应用程序时,它没有加载css和png文件。
在html文件中进行更改
<link rel="stylesheet" type="text/css" href="styles.css">
The way you have included the css will not work. 您包含CSS的方式将不起作用。 Lets assume you have put the style.css file in a folder named Styles in the root directory and in the root directory you have your server entry point index.js.
假设您已将style.css文件放置在根目录中名为Styles的文件夹中,并且在根目录中具有服务器入口点index.js。
you have to first host this directory as a static folder this is done by adding the following line in your index.js 您必须首先将此目录托管为静态文件夹,方法是在index.js中添加以下行
app.use("/Styles", express.static(path.join(__dirname, './Styles')));
This will allow you to access the files inside this directory after hosting 托管后,您将可以访问此目录中的文件
you can access the file using the url 您可以使用网址访问文件
http://localhost:3000/Styles/styles.css
Add this url to your to your html 将此网址添加到您的HTML中
<link rel="stylesheet" type="text/css" href="http://localhost:3000/Styles/styles.css">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.