我使用create-react-app
工具用react-routes
构建我的第一个反应应用程序,现在我想使用服务器端渲染来避免一次加载所有页面。
我按照指南安装了express.js,将客户端和服务器端与.js文件分开并用
运行NODE_ENV=production babel-node --presets 'react,es2015' src/server.js
但是当app试图编译sass @import语句时我收到错误。我想我必须首先提供资源,但我不知道如何在server.js逻辑中插入webpack函数
create-react-app还有用于生成构建的npm run build
命令并创建js和css文件,所以在编译server.js时可能有一些方法可以跳过资产部分吗?
Server.js 文件内容
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';
// initialize the server and configure support for ejs templates
const app = new Express();
const server = new Server(app);
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// define the folder that will be used for static assets
app.use(Express.static(path.join(__dirname, 'static')));
// universal routing and rendering
app.get('*', (req, res) => {
match(
{ routes, location: req.url },
(err, redirectLocation, renderProps) => {
// in case of error display the error message
if (err) {
return res.status(500).send(err.message);
}
// in case of redirect propagate the redirect to the browser
if (redirectLocation) {
return res.redirect(302, redirectLocation.pathname + redirectLocation.search);
}
// generate the React markup for the current route
let markup;
if (renderProps) {
// if the current route matched we have renderProps
markup = renderToString(<RouterContext {...renderProps}/>);
} else {
// otherwise we can render a 404 page
markup = renderToString(<NoMatch/>);
res.status(404);
}
// render the index template with the embedded React markup
return res.render('index', { markup });
}
);
});
// start the server
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://localhost:${port} [${env}]`);
});
答案 0 :(得分:0)
尝试安装node-sass
并遵循官方指南
https://create-react-app.dev/docs/adding-a-sass-stylesheet/