Next.js 和 SSR:构建高性能服务器渲染应用程序

1. 创建项目

使用 create-next-app 脚手架创建一个新的 Next.js 项目:

npx create-next-app my-app
cd my-app

2. 自动 SSR

在 Next.js 中,.js 或 .jsx 文件的每个组件都会自动处理为 SSR 页面。例如,创建一个 pages/index.js 文件:

// pages/index.js
import React from 'react';

function Home() {
  return (
    

Welcome to Next.js with SSR!

This is rendered on the server.

); } export default Home;

运行`npm run dev`启动开发服务器,访问`http://localhost:3000`,你会发现HTML已经包含了服务端渲染的内容。

3. 动态路由和数据采集

Next.js 支持动态路由,例如 `pages/posts/[id].js`。在 `getStaticPaths` 和 `getStaticProps` 或 `getServerSideProps` 中获取数据:

// pages/posts/[id].js
import { useRouter } from 'next/router';
import { getPostById } from '../lib/api'; // Custom API to obtain data

export async function getServerSideProps(context) {
  const id = context.params.id;
  const post = await getPostById(id);

  return {
    props: {
      post,
    },
  };
}

function Post({ post }) {
  const router = useRouter();
  if (!router.isFallback && !post) {
    router.push('/404');
    return null;
  }

  return (
    

{post.title}

{post.content}

); } export default Post;

4.静态优化与预渲染

Next.js 还支持静态优化与预渲染(Static Site Generation,SSG),在 getStaticPaths 和 getStaticProps 中配置:

// pages/posts/[id].js
export async function getStaticPaths() {
  // Get all possible dynamic paths
  const paths = await getPostIds();

  return {
    paths: paths.map((id) => `/posts/${id}`),
    fallback: false, // Or 'true' to return 404 for non-prerendered paths
  };
}

export async function getStaticProps(context) {
  const id = context.params.id;
  const post = await getPostById(id);

  return {
    props: {
      post,
    },
  };
}

6. 动态导入和代码分割

Next.js 支持动态导入,有助于按需加载代码并减少初始加载时间:

// pages/index.js
import dynamic from 'next/dynamic';

const DynamicComponent = dynamic(() => import('../components/Dynamic'), {
  ssr: false, // Avoid rendering on the server
});

function Home() {
  return (
    

Welcome to Next.js with SSR!

); } export default Home;

7. 优化图片和资源

使用 next/image 组件优化图片加载、自动压缩和调整大小:

// pages/index.js
import Image from 'next/image';

function Home() {
  return (
    

Welcome to Next.js with SSR!

Example Image
); } export default Home;

8. 自定义服务器

如果您需要更细粒度的控制,您可以创建自定义服务器:

// server.js
const { createServer } = require('http');
const { parse } = require('url');
const next = require('next');

const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();

app.prepare().then(() => {
  createServer((req, res) => {
    // Be sure to pass `true` as the second argument to `url.parse`.
    // This tells it to parse the query portion of the URL.
    const parsedUrl = parse(req.url, true);
    const { pathname } = parsedUrl;

    if (pathname === '/api') {
      // Custom API route handling
      // ...
    } else {
      handle(req, res, parsedUrl);
    }
  }).listen(3000, (err) => {
    if (err) throw err;
    console.log('> Ready on http://localhost:3000');
  });
});

9.集成第三方库和框架

Next.js 允许您轻松集成第三方库和框架,例如 Redux、MobX、Apollo 等:

// pages/_app.js
import React from 'react';
import App from 'next/app';
import { Provider } from 'react-redux';
import store from '../store';

function MyApp({ Component, pageProps }) {
  return (
    
      
    
  );
}

export default MyApp;

10.优化SEO

Next.js 的 SSR 功能对 SEO 很友好,但你也可以通过元标记进行优化:

// pages/index.js
import Head from 'next/head';

function Home() {
  return (
    <>
      
        My Next.js App
        
      
      

Welcome to Next.js with SEO!

); } export default Home;

11. 国际化(i18n)

Next.js 10 引入了内置的 i18n 支持,可以轻松实现多语言网站:

// next.config.js
module.exports = {
  i18n: {
    locales: ['en', 'fr'],
    defaultLocale: 'en',
  },
};

12.无服务器模式

Next.js 支持 Serverless 模式,该模式在 Vercel 上默认启用。在此模式下,你的应用程序将按需运行,从而节省资源成本。

13. Web Workers

使用 Next.js 中的 Web Workers 处理密集计算任务,避免阻塞主线程:

// components/Worker.js
import { useEffect } from 'react';
import { createWorker } from 'workerize-loader!./my-worker.js'; // Use workerize-loader to load worker files

function MyComponent() {
  const worker = createWorker();

  useEffect(() => {
    const result = worker.calculate(100000); // Calling worker methods
    result.then(console.log);
    return () => worker.terminate(); // Cleaning up workers
  }, []);

  return 
Loading...
; } export default MyComponent;

14. TypeScript 集成

Next.js 支持 TypeScript,为你的项目添加类型安全:

安装“typescript”和“@types/react”。

创建一个 `tsconfig.json` 配置文件。

修改“next.config.js”以启用 TypeScript 支持。

15. 自定义错误页面

创建 `pages/_error.js` 自定义错误页面:

// pages/_error.js
function Error({ statusCode }) {
  return (
    

Error {statusCode}

Something went wrong.

); } Error.getInitialProps = ({ res, err }) => { const statusCode = res ? res.statusCode : err ? err.statusCode : 404; return { statusCode }; }; export default Error;

16. 部署至 Vercel

Next.js 与 Vercel 完美集成。只需几个简单的步骤即可部署它:

创建帐户或登录 Vercel 网站。

授权 Vercel 访问您的 GitHub 或 GitLab 存储库。

选择要部署的项目,Vercel 将自动检测 Next.js 配置。

设置项目域名和环境变量(如有必要)。

单击“部署”按钮,Vercel 将自动构建并部署应用程序。

17. 性能监控与优化

使用 Next.js 内置的 Lighthouse 插件或者 Google PageSpeed Insights 等第三方工具进行性能评估,根据报告对代码、图片等资源进行优化,提升加载速度和用户体验。