在服务器端渲染ReactJs上渲染CSS

时间:2019-03-04 04:47:21

标签: javascript css reactjs express serverside-rendering

我正在开发服务器端渲染的reactjs应用程序。一切正常,但是我遇到了一个问题,那就是在第一次加载时渲染css需要时间(仅在html加载内容之后才加载css)。我尝试了{ {3}}。

Client.js

import './../../node_modules/bootstrap/dist/css/bootstrap.css';
import './styles/css/main.css';

const initialState = fromJS(window.__INITIAL_STATE__) ;
const Store = createStore(
  reducers,
  initialState,
  applyMiddleware(thunk.withExtraArgument(axiosInstance))
);

hydrate(  
  <Provider store={Store}>
    <BrowserRouter>
      <div>
        {renderRoutes(Routes)}
        <Footer/>
      </div>
    </BrowserRouter>  
  </Provider>,
  document.querySelector('#root')
);

Server.js

import renderer from './helpers/renderer';

const app = express();
app.use(express.static('public'));
app.use(bodyParser.urlencoded({
  extended: true
}));

app.get('*', (req, res) => {
  const store = createStore(req);  
  const promises = matchRoutes(Routes, req.path)
    .map(({ route, match }) => {

      var parts = req.path.split("/");
      var lastSegment = parts.pop() || parts.pop();
      return route.loadData ? route.loadData(store, lastSegment) : null;
    })
    .map(promise => {
      if (promise) {        
        return new Promise((resolve, reject) => {
          promise.then(resolve).catch(resolve);
        });
      }
    });
  Promise.all(promises).then(() => {
     const context = {};
    const content = renderer(req, store, context);
    if (context.url) {
      return res.redirect(301, context.url);
    }
    if (context.notFound) {
      res.status(404);
    }   
    res.send(content);    
  });
});

app.listen(SERVER_PORT, () => {
  console.log('Listening on port '+SERVER_PORT);
});

Renderer.js

我试图从rendere.js加载所有的css文件,但没有帮助,重新加载页面时html正文部分消失了。

export default (req, store, context) => {
  const content = renderToString(
    <Provider store={store} >
      <StaticRouter location={req.path} context={context}>
        <div>{renderRoutes(Routes)}</div>
      </StaticRouter>
    </Provider>
  );

  const helmet = Helmet.renderStatic();
  return `<!doctype html>
    <html lang="en"> 
      <head>
      <link rel="shortcut icon" href="fav.png">
        <meta name="viewport" content="width=device-width, initial-scale=1">        
        ${helmet.title.toString()}
        ${helmet.meta.toString()}            
        </head>
      <body>
      <base href="/" />
        <div id="root">${content.toString()}</div>
        <script>
          window.INITIAL_STATE = ${serialize(store.getState())}
        </script>

        <script src="bundle.js"></script>
      </body>
    </html>
  `;
};

0 个答案:

没有答案