Next.js 使用指南3-高级配置

本文是Next.js使用指南系列的第三篇,主要介绍如何进行高级配置,包括组件覆写、异常处理、自定义配置文件、Webpack和Babel配置,以及静态HTML输出、CDN前缀支持等。通过这些配置,你可以更好地掌控Next.js应用的开发和部署。
摘要由CSDN通过智能技术生成

书接上文 Next.js 使用指南2-路由与加载,到这里,恭喜你已经完成了大部分的学习,基本使用已经足够。何不锦上添花,顺势拿下最难啃的部分呢?

一、关于组件

App 组件一样,document 组件也可以被覆写,这时我们需要创建 .pages/_document.js 文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// _document is only rendered on the server side and not on the client side
// Event handlers like onClick can't be added to this file

// ./pages/_document.js
import Document, { Head, Main, NextScript } from 'next/document'

export default class MyDocument extends Document {
static async getInitialProps(ctx) {
const initialProps = await Document.getInitialProps(ctx)
return { ...initialProps }
}

render() {
return (
<html>
<Head>
<style>{ `body { margin: 0 } /* custom! */`}</style>
</Head>
<body className="custom_class">
<Main />
<NextScript />
</body>
</html>
)
}
}

Pages in Next.js skip the definition of the surrounding document’s markup. For example, you never include ,

, etc.
二、异常处理

Nextjs 中有默认的 error.js 文件,如果 404 或者 500 都会加载 error 组件。当然,该组件也可以被覆写。例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 创建_error.js 文件:
import React from 'react'

export default class Error extends React.Component {
static getInitialProps({ res, err }) {
const statusCode = res ? res.statusCode : err ? err.statusCode : null;
return { statusCode }
}

render() {
return (
<p>
{
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值