I use the tool create-react-appto create my first responsive application with react-routes, and now I would like to use server-side rendering so as not to load all pages at once.
I followed the manuals and installed express.js, separated the client and server sides with .js files and ran them using
NODE_ENV=production babel-node --presets 'react,es2015' src/server.js
But I get an error when the application tries to compile @import sass instructions. I think I need to service the assets first, but I don't know how to embed webpack functions in server.js logic
create-react-app also has a command npm run buildto build the assembly and create js and css files, so maybe there is a way to skip parts of the assets when compiling server.js?
Server.js Server Content
import path from 'path';
import { Server } from 'http';
import Express from 'express';
import React from 'react';
import { renderToString } from 'react-dom/server';
import { match, RouterContext } from 'react-router';
import routes from './routes';
import NoMatch from './pages/NoMatch';
const app = new Express();
const server = new Server(app);
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use(Express.static(path.join(__dirname, 'static')));
app.get('*', (req, res) => {
match(
{ routes, location: req.url },
(err, redirectLocation, renderProps) => {
if (err) {
return res.status(500).send(err.message);
}
if (redirectLocation) {
return res.redirect(302, redirectLocation.pathname + redirectLocation.search);
}
let markup;
if (renderProps) {
markup = renderToString(<RouterContext {...renderProps}/>);
} else {
markup = renderToString(<NoMatch/>);
res.status(404);
}
return res.render('index', { markup });
}
);
});
const port = process.env.PORT || 3000;
const env = process.env.NODE_ENV || 'production';
server.listen(port, err => {
if (err) {
return console.error(err);
}
console.info(`Server running on http:
});
source
share