我无法从documentation中找到答案。
我正在尝试通过styled-components向我的服务器端渲染React应用程序添加一些全局样式 - 但我无法弄清楚如何执行此操作。
以下是globalStyles.js
的部分内容:
import { injectGlobal } from 'styled-components';
export default () => injectGlobal`
@import url('https://fonts.googleapis.com/css?family=Pacifico');
@import url('https://fonts.googleapis.com/css?family=Open+Sans:300,400');
html {
box-sizing: border-box;
}
*, *:before, *:after {
box-sizing: inherit;
}
`;
这是我的普遍渲染表达式处理程序:
const path = require('path');
const fs = require('fs');
const React = require('react');
const { renderToString } = require('react-dom/server');
const { StaticRouter } = require('react-router-dom');
const { ServerStyleSheet } = require('styled-components');
const { default: App } = require('../src/containers/App');
const baseStyles = require('../src/styles'); // How to get this in the global css
const indexFile = fs.readFileSync(path.resolve(__dirname, '..', 'build', 'index.html'), 'utf8');
function universalLoader(req, res) {
const css = new ServerStyleSheet();
const context = {};
baseStyles();
// Create the markup from the React application
const markup = renderToString(
css.collectStyles(
<StaticRouter context={context} location={req.url}>
<App />
</StaticRouter>
)
);
const html = indexFile
.replace('{{SSR}}', markup)
.replace('{{CSS}}', css.getStyleTags());
// Send the response back to the user
res.send(html);
};
答案 0 :(得分:2)
事实证明,在baseStyles()
组件injectGlobal
方法中调用<App />
(后者正在调用render()
)修复了问题。 :)