Next.js 开发入门指南

快速入门 Next.js 框架, 精简记录手册§(* ̄▽ ̄*)§

0%

Site: https://nextjs.org
Docs: https://nextjs.org/docs
React: https://reactjs.org/tutorial/tutorial.html

简单了解

一个 React 框架, 提供了创建 Web 应用程序的构建程序.

创建项目

npx create-next-app@latest
# or
yarn create next-app

运行项目

npm run dev
# or
yarn dev

组件

常用

  • Router

    import { useRouter } from 'next/router'
  • Link

    import Link from 'next/link';
  • Image

    import Image from 'next/image'
  • Head

    import Head from 'next/head';
  • Script

    import Script from 'next/script';

日期处理

安装库

npm install date-fns

例子

import { parseISO, format } from 'date-fns';

export default function Date({ dateString }) {
const date = parseISO(dateString);
return <time dateTime={dateString}>{format(date, 'LLLL d, yyyy')}</time>;
}

CSS

使用 CSS Modules, CSS文件名必须以.module.css.

安装 Tailwind CSS -> https://tailwindcss.com/

npm install -D tailwindcss autoprefixer postcss

添加 postcss.config.js 到项目根目录.

// postcss.config.js
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};

添加 tailwind.config.js 到项目根目录.

// tailwind.config.js
module.exports = {
content: [
'./pages/**/*.{js,ts,jsx,tsx}',
'./components/**/*.{js,ts,jsx,tsx}',
// For the best performance and to avoid false positives,
// be as specific as possible with your content configuration.
],
};

组件动态导入

import dynamic from 'next/dynamic';

引入组件, 服务器上不需要加载, 设置ssrfalse.

const CodeSampleModal = dynamic(() => import('../components/CodeSampleModal'), {
ssr: false,
});

包装组件

{
isModalOpen && (
<CodeSampleModal
isOpen={isModalOpen}
closeModal={() => setIsModalOpen(false)}
/>
);
}

数据获取

Data Fetching: Overview | Next.js (nextjs.org)

getStaticProps

  • 生成静态页面路径
  • 在函数内部, 可以获取外部数据并将其作为变量传递到页面.
  • 开发模式, 每个请求都会运行; 生产环境中,只在构建时运行.
  • 只能在page 文件中使用.(pages文件夹下的.js,.jsx,.ts,.tsx文件)
export default function Home(props) { ... }

export async function getStaticProps() {
// Get external data from the file system, API, DB, etc.
const data = ...

// The value of the `props` key will be
// passed to the `Home` component
return {
props: ...
}

API获取数据

export async function getSortedPostsData() {
// Instead of the file system,
// fetch post data from an external API endpoint
const res = await fetch('..');
return res.json();
}

从数据库获取数据

import someDatabaseSDK from 'someDatabaseSDK'

const databaseClient = someDatabaseSDK.createClient(...)

export async function getSortedPostsData() {
// Instead of the file system,
// fetch post data from a database
return databaseClient.query('SELECT posts...')
}

getStaticProps

  • 生成静态页面内容
export async function getStaticProps(context) {
return {
props: {}, // will be passed to the page component as props
}
}

getServerSideProps

  • 服务器端渲染数据, 每个请求都会运行
  • Data Fetching: Overview | Next.js (nextjs.org)
export async function getServerSideProps(context) {
return {
props: {
// props for your component
},
};
}

SWR

用于数据请求的 React Hooks 库 – SWR

  • 使用 SWR,组件将会不断地自动获得最新数据流。
  • UI 也会一直保持快速响应
import useSWR from 'swr';

function Profile() {
const { data, error } = useSWR('/api/user', fetch);

if (error) return <div>failed to load</div>;
if (!data) return <div>loading...</div>;
return <div>hello {data.name}!</div>;
}

API Routes

API Routes: Introduction | Next.js (nextjs.org)

pages/api/hello.js - localhost:3000/api/hello

export default function handler(req, res) {
res.status(200).json({ text: 'Hello' });
}
  • req 是 http. IncomingMessage 的一个实例,加上一些预构建的中间件。
  • res 是 http. ServerResponse 的一个实例,外加一些 helper 函数。

搜索引擎优化

谷歌爬虫工作流

  1. Find URLs - 查找URL 从站点地图(XML), 页面链接等.

  2. Add to Crawl Queue - 添加到爬取队列等待爬取.

  3. HTTP Request - 发送请求URL, 根据响应状态码做不同的处理.

    • 200 - 请求成功

    • 301/308 - 永久重定向 308为推荐的处理(不允许更改请求方法)

      //  pages/about.js
      export async function getStaticProps(context) {
      return {
      redirect: {
      destination: '/',
      permanent: true, // triggers 308
      },
      };
      }
    • 302 - 临时重定向

    • 404 - 不存在页面
      指定返回 404 状态码

      export async function getStaticProps(context) {
      return {
      notFound: true, // triggers 404
      };
      }

      定制 404 页面

      // pages/404.js
      export default function Custom404() {
      return <h1>404 - Page Not Found</h1>;
      }
    • 410 - 永久删除的内容(通知爬虫不再抓取)

    • 500 - 服务器错误
      定制 500 页面

      // pages/500.js
      export default function Custom500() {
      return <h1>500 - Server-side error occurred</h1>;
      }
    • 503 - 预计网站会关闭一段时间时(可以保持排名)

  4. Render Queue - 页面存在JavaScript内容 添加到渲染队列(需要更长的时间).

  5. Ready to be indexed - 满足条件则添加索引到数据库.

robots.txt 文件

直接放在项目根目录即可

//robots.txt

# Block all crawlers for /accounts
User-agent: *
Disallow: /accounts

# Allow all crawlers
User-agent: *
Allow: /

站点地图 - Sitemaps

  • 方便爬取
  • 有丰富内容的站点必备

使用 getServerSideProps 动态生成

//pages/sitemap.xml.js
const EXTERNAL_DATA_URL = 'https://jsonplaceholder.typicode.com/posts';

function generateSiteMap(posts) {
return `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<!--We manually set the two URLs we know already-->
<url>
<loc>https://jsonplaceholder.typicode.com</loc>
</url>
<url>
<loc>https://jsonplaceholder.typicode.com/guide</loc>
</url>
${posts
.map(({ id }) => {
return `
<url>
<loc>${`${EXTERNAL_DATA_URL}/${id}`}</loc>
</url>
`;
})
.join('')}
</urlset>
`;
}

function SiteMap() {
// getServerSideProps will do the heavy lifting
}

export async function getServerSideProps({ res }) {
// We make an API call to gather the URLs for our site
const request = await fetch(EXTERNAL_DATA_URL);
const posts = await request.json();

// We generate the XML sitemap with the posts data
const sitemap = generateSiteMap(posts);

res.setHeader('Content-Type', 'text/xml');
// we send the XML to the browser
res.write(sitemap);
res.end();

return {
props: {},
};
}

export default SiteMap;

特定的元标签 - Special Meta Tags

https://developers.google.com/search/docs/advanced/robots/robots_meta_tag#directives

import Head from 'next/head';

function IndexPage() {
return (
<div>
<Head>
<title>Meta Tag Example</title>
<meta name="google" content="nositelinkssearchbox" key="sitelinks" />
<meta name="google" content="notranslate" key="notranslate" />
</Head>
<p>Here we show some meta tags off!</p>
</div>
);
}

export default IndexPage;

规范标签 - Canonical Tags

What are Canonical Tags? - Crawling and Indexing | Learn Next.js (nextjs.org)

渲染和排名 - Rendering and Ranking

渲染策略 - Rendering Strategies

  • 静态站点生成(SSG) - Static site generation
    预渲染页面, 在构建时生成HTML, 有助于页面性能提升.

  • 服务器端呈现(SSR) - Server-Side Rendering
    也是预渲染页面, 不同是在每次请求时生成, 这对于具有非常动态的页面非常有用.

  • 增量静态再生(ISR) - Incremental Static Regeneration
    可以在构建站点之后创建或更新静态页面, 适合拥有大量的页面的网站, 在扩展到数百万页面的同时保留静态的好处。

  • 客户端呈现(CSR) - Client-Side Rendering
    使用 JavaScript 在浏览器中完全渲染网站, 不利于搜索引擎, 适用于数据量大的仪表板、账户页面或任何不需要出现在任何搜索引擎索引中的页面。

网址结构 - URL Structure

  • 使 URL 具有语义
    如: /learn/basics/create-nextjs-app/learn/course-1/lesson-1 写法更好.

  • 逻辑性和一致性
    如, 对路径分组, 产品放产品路径下.

  • 使用关键词
    如: Next文章URL中包含 next 关键字.

  • 不使用参数构建 URL

    大多数情况下,它们不具有语义,搜索引擎可能会混淆它们,从而降低它们在搜索结果中的排名.

元数据 - Metadata

  • 标题 - Title
    最重要的 SEO 元素之一.
  • 描述 - Description
    不影响排名, 但影响用户点击率.
  • 打开图表 - Open Graph protocol
    用于添加分享时内容丰富程度, 不影响排面, 但有利于点击.

Next.js 中的例子:

import Head from 'next/head';

function IndexPage() {
return (
<div>
<Head>
<title>Cool Title</title>
<meta name="description" content="Checkout our cool page" key="desc" />
<meta property="og:title" content="Social Title for Cool Page" />
<meta
property="og:description"
content="And a social description for our cool page"
/>
<meta
property="og:image"
content="https://example.com/images/cool-page.jpg"
/>
</Head>
<h1>Cool Page</h1>
<p>This is a cool page. It has lots of cool content!</p>
</div>
);
}

export default IndexPage;

结构化数据 - Structured Data

schema.org

网站指标

Web 指标
Chrome UX Report - Chrome Developers

  • Largest Contentful Paint (LCP) :最大内容绘制,测量加载性能。为了提供良好的用户体验,LCP 应在页面首次开始加载后的2.5 秒内发生。
  • First Input Delay (FID) :首次输入延迟,测量交互性。为了提供良好的用户体验,页面的 FID 应为100 毫秒或更短。
  • Cumulative Layout Shift (CLS) :累积布局偏移,测量视觉稳定性。为了提供良好的用户体验,页面的 CLS 应保持在 0.1. 或更少。

使用谷歌开发者工具 Lighthouse 生成分析报告

  1. 打开隐私窗口
  2. 进入 https://nextjs.org/
  3. F12 调用开发者工具 -> 打开 Lighthouse选项卡 -> 点击Analyze page load 按钮
  4. 等待分析完成, 出现分析结果.

测试工具

  • PageSpeed Insights
  • Chrome User Experience Report
  • Search Console

TypeScript

...

使用vercel部署项目

https://vercel.com/?utm_source=next-site&utm_medium=learnpages&utm_campaign=next-website

------------ 已触及底线了 感谢您的阅读 ------------
  • 本文作者: OWQ
  • 本文链接: https://www.owq.world/nextjs/
  • 版权声明: 本站所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处( ̄︶ ̄)↗