I'm doing server side rendering for my React JS App.But i cannot load .css and images to html file.
My directory structure
build
public
index.html
styles.css
fav.png
src
client
client.js
index.js
webpack.js
my index.html file
<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)
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
{
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.
在html文件中进行更改
<link rel="stylesheet" type="text/css" href="styles.css">
The way you have included the css will not work. 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.
you have to first host this directory as a static folder this is done by adding the following line in your 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
<link rel="stylesheet" type="text/css" href="http://localhost:3000/Styles/styles.css">
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.