undefined
前言
Next.js是一个构建于Node.js之上的开源Web开发框架,支持基于React的Web应用程序功能,例如服务端渲染和生成静态网站。(维基百科)
创建项目
1
| npx create-next-app@latest
|
环境变量
定义环境变量
- 使用全大写的蛇形命名环境变量,所有环境变量最终都存储在
process.env中
- 以
NEXT_PUBLIC_为前缀的环境变量允许在客户端读取
.env1 2
| KEY1="" NEXT_PUBLIC_KEY2=""
|
.env
读取环境变量
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| export default function Component() { if (typeof window === "object") { console.log("client"); console.log(process.env.NEXT_PUBLIC_KEY2); } else { console.log("server"); console.log(process.env.KEY1); console.log(process.env.NEXT_PUBLIC_KEY2); } return ( <></> ); }
|
配置文件
tsconfig.json
配置目录别名
tsconfig.json1 2 3 4 5 6 7
| { "compilerOptions": { "paths": { "@/components/*": ["components/*"] } } }
|
next.config.js
next.config.js中配置的环境变量nextConfig.env优先级最高,会覆盖.env
reactStrictMode:是否启用严格模式
env:环境变量
basePath:公共URL前缀
next.config.js1 2 3 4 5 6 7 8 9
| const nextConfig = { reactStrictMode: true, env: { KEY: "" }, basePath: "/" };
module.exports = nextConfig;
|
内置组件
单页面渲染
SEO组件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| import Head from "next/head"; import Script from "next/script"; import Link from "next/link";
export default function Component() { return ( <> <Head> <title></title> <link href=""></link> </Head> <Script src=""></Script> </> ); }
|
图片组件
引入本地图片
1 2 3 4 5 6 7 8 9 10
| import Image from "next/image"; import Img from "../assets/img.png";
export default function Component() { return ( <> <Image src={Img} alt={}></Image> </> ); }
|
引入网络图片
- 配置白名单
next.config.js1 2 3 4 5 6 7 8 9 10
| const nextConfig = { images: { remotePatterns: [ { protocol: "https", hostname: "**.example.com" } ] } }
|
- 引入网络图片Next.js不会自动识别图片的宽高,必须手动指定,或填充宽高到父容器
priority:预加载
fill:填充宽高到父容器
1 2 3 4 5 6 7 8 9 10
| import Image from "next/image";
export default function Component() { return ( <> <Image src={"http://example.com/img.png"} alt="" width={} height={} priority></Image> <Image src={"http://example.com/img.png"} alt="" fill></Image> </> ); }
|
所有页面渲染
SEO组件
pages/_document.tsx1 2 3 4 5 6 7 8 9 10 11 12 13
| import { Html, Head, Main, NextScript } from "next/document";
export default function Document() { return ( <Html> <Head /> <body> <Main /> <NextScript /> </body> </Html> ); }
|
CSS样式
全局CSS样式
- 在
styles/中定义CSS文件
styles/global.css
- 在
_app.tsx中引入CSS文件
pages/_app.tsx1
| import "../styles/global.css";
|
局部CSS样式
- 在
styles/中定义CSS文件
styles/component.module.css1 2 3
| .class-name { color: red; }
|
- 在JSX文件中引入CSS文件
pages/component.jsx1 2 3 4 5 6 7 8 9
| import styles from "../styles/Component.modules.css";
export default function Component() { return ( <> <div className={styles["class-name"]}></div> </> ); }
|
通过Sass定义CSS样式
下载依赖
全局CSS样式
- 在
styles/中定义Sass文件
styles/global.scss
- 在
_app.tsx中引入Sass文件
pages/_app.tsx1
| import "../styles/global.scss";
|
局部CSS样式
在Sass文件中使用Sass变量
- 在
styles/中定义Sass文件
styles/variable.scss
- 在Sass文件中使用Sass变量
styles/component.module.scss1 2 3 4 5
| @use "./variable.scss" as *;
.class-name { color: $mainColor; }
|
- 在JSX文件中引入Sass文件
pages/component.jsx1 2 3 4 5 6 7 8 9
| import styles from "../styles/Component.modules.scss";
export default function Component() { return ( <> <div className={styles["class-name"]}></div> </> ); }
|
在JSX文件中使用Sass变量
- 导出可在JSX文件中引入的Sass变量
styles/variable.module.scss1 2 3
| :export { mainColor: red; }
|
- 在JSX文件中引入并使用Sass变量
pages/component.jsx1 2 3 4 5 6 7 8 9
| import stylesVariable from "../styles/variable.module.scss";
export default function Component() { return ( <> <div style={{color: stylesVariable.mainColor}}></div> </> ); }
|
资源文件
public
在JSX文件中引入资源文件
1 2 3 4 5 6 7 8 9
| import Image from "next/image";
export default function Component() { return ( <> <Image src={"/img.png"} alt={} width={} height={}></Image> </> ); }
|
在CSS文件中引入资源文件
1 2 3
| * { background-image: url(/img.png); }
|
assets
1 2 3
| + assets + images - img.png
|
在JSX文件中引入资源文件
1 2 3 4 5 6 7 8 9 10
| import Image from "next/image"; import Img from "../assets/images/img.png";
export default function Component() { return ( <> <Image src={Img} alt={}></Image> </> ); }
|
字体图标
1 2 3 4
| + assets + iconfonts - iconfont.css - iconfont.ttf
|
assets/iconfonts/iconfont.css1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| @font-face { font-family: "iconfont"; src: url("assets/iconfonts/iconfont.ttf") format("truetype"); }
.iconfont { font-family: "iconfont" !important; font-size: 16px; font-size: normal; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; }
.icon-home:before { content: "\e600"; }
|
在JSX文件中引入字体图标
1 2 3 4 5 6 7 8 9
| import "../assets/iconfonts/iconfont.css";
export default function Component() { return ( <> <i className={"iconfont icon-home"}></i> </> ); }
|
路由
创建页面
- Next.js只能通过在
pages/中手动创建.js、.jsx、.tx、.tsx文件并导出React组件的方式创建页面
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| import { memo, ReactElement } from "react"; import type { FC } from "react";
export interface IProps { children?: ReactElement }
const Component: FC<IProps> = memo(function (props) { return ( <></> ); }); Component.displayName = "Component";
export default Component;
|
约定式路由
1 2 3
| + pages + home - index.jsx
|
1 2 3
| + pages + father - [key].jsx
|
嵌套路由
- 通过嵌套布局实现嵌套路由
- app目录和pages目录只能同时使用一种
启用app目录
1 2 3 4 5 6 7 8
| + app - head.tsx // 全局SEO - layout.tsx // 首页布局 - page.tsx // 首页 + other - head.tsx - layout.tsx - page.tsx
|
修改配置文件
next.config.js1 2 3 4 5
| const nextConfig = { experimental: { appDir: true } };
|
定义首页
app/head.tsx1 2 3 4 5 6 7
| export default function Head(props) { return ( <> <title></title> </> ); }
|
app/layout.jsx1 2 3 4 5 6 7 8
| export default function RootLayout(props) { return ( <html> <head /> <body>{props.children}</body> </html> ); }
|
app/page.jsx1 2 3 4 5 6 7 8
| const Home = function (props) { return ( <></> ); }; Home.displayName = "Home";
export default Home;
|
定义父级页面
app/father/head.tsx1 2 3 4 5 6 7
| export default function Head(props) { return ( <> <title></title> </> ); }
|
app/father/layout.jsx1 2 3 4 5 6 7
| export default function FatherLayout(props) { return ( <div> {props.children} </div> ); }
|
app/father/page.jsx1 2 3 4 5 6 7 8
| const Father = function (props) { return ( <></> ); }; Father.displayName = "Father";
export default Father;
|
定义子级页面
app/father/son/head.tsx1 2 3 4 5 6 7
| export default function Head() { return ( <> <title></title> </> ); }
|
app/father/son/layout.jsx1 2 3 4 5 6 7
| export default function SonLayout(props) { return ( <div> {props.children} </div> ); }
|
app/father/son/page.jsx1 2 3 4 5 6 7 8
| const Son = function (props) { return ( <></> ); }; Son.displayName = "Son";
export default Son;
|
404页面
任意路径下的404页面
1 2
| + pages - [...slug].jsx
|
pages/[...slug].jsx1 2 3 4 5 6 7 8
| export default function Component(props) { const router = useRouter(); const { slug } = router.query; console.log(slug); return ( <>404</> ); }
|
项目根目录下的404页面
pages/404.jsx1 2 3 4 5
| export default function Component(props) { return ( <>404</> ); }
|
项目根目录下的500页面
pages/500.jsx1 2 3 4 5
| export default function Component(props) { return ( <>404</> ); }
|
路由跳转
通过组件跳转路由
<Link></Link>是对router-link的封装
<Component {...pageProps} />是对router-view的封装
href:定义跳转目标
as:路径别名,在访问后会URL会显示别名
replace:改为替换路由而不是跳转路由
target:以何种方式打开新的页面
_self:缺省值,在当前页面打开页面
_blank:在新的页面打开页面
pages/_app.tsx1 2 3 4 5 6 7 8 9 10 11 12 13
| import type { AppProps } from "next/app"; import Link from "next/link";
export default function App({ Component, pageProps }: AppProps) { return ( <> <Link href={"/home"}> <button>首页</button> </Link> <Component {...pageProps} /> </> ); }
|
pathname:路径
query:指定查询字符串
pages/_app.tsx1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| import type { AppProps } from "next/app"; import Link from "next/link";
export default function App({ Component, pageProps }: AppProps) { return ( <> <Link href={{ pathname: "/home", query: { key: "value" } }}> <button>首页</button> </Link> <Component {...pageProps} /> </> ); }
|
通过js跳转路由
useRouter()
有历史记录的跳转
- 第一个参数是路径
- 第二个参数是别名
- 第三个参数是其他参数
1 2 3 4 5 6 7 8 9
| import { useRouter } from "next/router";
export default function Component(props) { const router = useRouter(); router.push("/home"); return ( <></> ); }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| import { useRouter } from "next/router";
export default function Component(props) { const router = useRouter(); router.push({ puthname: "/home", query: { key: "value" } }); return ( <></> ); }
|
无历史记录的跳转
- 第一个参数是路径
- 第二个参数是别名
- 第三个参数是其他参数
1 2 3 4 5 6 7 8 9
| import { useRouter } from "next/router";
export default function Component(props) { const router = useRouter(); router.replace("/home"); return ( <></> ); }
|
向后
1 2 3 4 5 6 7 8 9
| import { useRouter } from "next/router";
export default function Component(props) { const router = useRouter(); router.back(); return ( <></> ); }
|
客户端路由的监听
事件
routeChangeStart:路由切换开始
routeChangeComplate:路由切换完成
pages/_app.tsx1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| import type { AppProps } from "next/app"; import { useRouter } from "next/router";
export default function App({ Component, pageProps }: AppProps) { const router = useRouter(); useEffect(function () { const handleRouteChangeStart = function (url) { console.log(url); }; router.events.on("routeChangeStart", handleRouteChangeStart); return function () { router.events.off("routeChangeStart", handleRouteChangeStart); } }, []); return ( <></> ); }
|
获取path参数
- 文件名使用
[]定义参数的key,并且[]的前后不能有其他字符串
1
| http://example.com/father/value
|
pages/father/[key].jsx1 2 3 4 5 6 7 8 9 10
| import { useRouter } from "next/router";
export default function Component(props) { const router = useRouter(); const { key } = router.query; console.log(key); return ( <></> ); }
|
1
| http://example.com/value1/value2
|
pages/[key1]/[key2].jsx1 2 3 4 5 6 7 8 9 10 11
| import { useRouter } from "next/router";
export default function Component(props) { const router = useRouter(); const { key1, key2 } = router.query; console.log(key1); console.log(key2); return ( <></> ); }
|
获取查询字符串
1
| http://example.com/?key=value
|
1 2 3 4 5 6 7 8 9 10
| import { useRouter } from "next/router";
export default function Component(props) { const router = useRouter(); const { key } = router.query; console.log(key); return ( <></> ); }
|
- 由于获取path参数和获取查询字符串都是通过
query属性获取,所以在path参数和查询字符串的key相同时,优先获取path参数的值作为value
1
| http://example.com/father/value1?key=value2
|
pages/father/[key].jsx1 2 3 4 5 6 7 8 9 10
| import { useRouter } from "next/router";
export default function Component(props) { const router = useRouter(); const { key } = router.query; console.log(key); return ( <></> ); }
|
中间件和匹配器
返回规则
NextResponse.next():放行
NextResponse.redirect(""):请求重定向
NextResponse.redirect(new URL("/", request.nextUrl.origin)):请求重定向
NextResponse.rewrite(""):请求重写
mather:定义匹配器匹配规则
middleware.tsx1 2 3 4 5 6 7 8 9
| import { NextRequest, NextResponse } from "next/server";
export function middleware(request: NextRequest) { return NextResponse.next(); };
export const config = { mather: ["/father/:path*"] };
|
请求
获取请求URL
1
| const result = request.url;
|
1
| const result = request.nextUrl;
|
获取pathname
1
| const result = request.nextUrl.pathname;
|
获取Cookie
1
| const result = request.cookies.get("key")?.value;
|
Cookie
下载依赖
1
| npm install cookies-next
|
设置Cookie
1 2 3
| import { setCookie } from "cookies-next";
setCookie("key", "value", { maxAge: 10 });
|
获取Cookie
1 2 3
| import { getCookie } from "cookies-next";
const value = getCookie("key");
|
布局
components/layout/index.jsx1 2 3 4 5 6 7 8 9
| export default function Layout(props) { return ( <> <div> {props.children} </div> </> ); }
|
pages/_app.tsx1 2 3 4 5 6 7 8 9 10
| import type { AppProps } from "next/app"; import Layout from "../component/layout";
export default function App({ Component, pageProps }: AppProps) { return ( <Layout> <Component {...pageProps} /> </Layout> ); }
|
组件的生命周期
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| import { Component, ReactNode } from "react";
class Home extends Component { constructor(props) { super(props); } UNSAFE_componentWillMount() {} componentDidMount() {} componentWillUnmount() {} render() { return ( <></> ); } }
export default Home;
|
1 2 3 4 5 6 7 8 9 10
| export default function Home(props) {
useEffect(function () { return function () {} }, []); return ( <></> ); }
|
服务器
request1
| GET http://127.0.0.1:80/api/home
|
pages/api/home.js1 2 3 4 5
| export default function handler(request, response) { response.status(200).send({ data: "value" }); }
|
请求对象
获取请求方法
1
| const result = request.method;
|
获取请求URL
1
| const result = request.url;
|
获取查询字符串
1
| const result = request.query;
|
获取请求体
1
| const result = request.body;
|
响应对象
返回200
1 2 3
| response.status(200).send({ data: "value" });
|
返回500
1
| response.status(500).end();
|
静态站点生成(Static Site Generation, SSG)
页面内容取决于外部数据
getValueById():从后端获取的外部数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| export default function Component(props) { const value = props.key; return ( <></> ); }
export const getStaticProps = function (context) { const value = getValueById(context.params.id); return { props: { key: value } } }
|
页面总数取决于外部数据
fallback:回调
false:匹配失败返回404页面
pages/component/[id].jsx1 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 27 28 29 30 31
| import { useRouter } from "next/router";
export default function Component(props) { const value = props.key2; return ( <></> ); }
export const getStaticPaths = function () { const router = useRouter(); const value = getValueById(router.query.id); return { paths: [ { props: { key1: value } } ], fallback: false } }
export const getStaticProps = async function (context) { return { props: { key2: context.params.key1 } } }
|
服务端渲染(Server-Side Rendering, SSR)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| export default function Component(props) { const value = props.key; return ( <></> ); }
export const getServerSideProps = function (context) { const query = context.query; return { props: { key: "value" } } }
|
增量静态再生成(Incremental Static Regeneration, ISR)
revalidate:缓存有效期,如果某一次访问超过了有效期,当前访问是旧数据,并立即渲染新数据,下一次访问是新数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| export default function Component(props) { const value = props.key; return ( <></> ); }
export const getStaticProps = function (context) { return { props: { key: "value" }, revalidate: 1 } }
|
客户端渲染(Client-Side Rendering, CSR)
1 2 3 4 5 6 7 8 9 10 11 12
| export default function Component(props) {
const [value, setValue] = useState(null); useEffect(function () { setValue("value"); }, []); return ( <></> ); }
|
完成