【发布时间】:2020-10-17 22:39:27
【问题描述】:
我有针对不同布局的自定义 CSS 文件,在开发模式下没有问题,但是当我在生产模式下发布我的应用程序时,Nextjs 结合了所有 CSS 并为我的布局带来了问题。
【问题讨论】:
标签: css reactjs webpack next.js
我有针对不同布局的自定义 CSS 文件,在开发模式下没有问题,但是当我在生产模式下发布我的应用程序时,Nextjs 结合了所有 CSS 并为我的布局带来了问题。
【问题讨论】:
标签: css reactjs webpack next.js
通常,在build 之后,我们将所有CSS 和JS chunks 推送到static 文件夹中,以便当服务器请求请求的页面Next Js 时,从该static 文件夹中提供它(取决于应要求)。
Server.js:
const staticDir = path.resolve(__dirname, "..", ".next/static");
server.use(compression());
server.use("/_next/static", express.static(staticDir));
server.get("/_next/*", (req, res) => {
/* serving _next static content using next.js handler */
handle(req, res);
});
server.get("/static/*", (req, res) => {
/* serving _next static content using next.js handler */
handle(req, res);
});
在您的_document.js 文件中添加以下行,并请分享您在next.config.js 中添加的配置。
_document.js
// 渲染应用程序和页面并获取页面的上下文以及收集的副作用。
const sheets = new ServerStyleSheets();
const originalRenderPage = ctx.renderPage;
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: App => props => sheets.collect(<App {...props} />)
});
const initialProps = await Document.getInitialProps(ctx);
return {
...initialProps,
// Styles fragment is rendered after the app and page rendering finish.
styles: [
...React.Children.toArray(initialProps.styles),
sheets.getStyleElement()
]
};
};
【讨论】: