React server-side rendering framework: Next.js

React server-side rendering framework: Next.js

Article source: Lagou big front-end high-paying training camp

Practice code address

Next.js is a React server-side rendering application framework. It is used to build SEO friendly SPA applications.

  1. Supports two pre-rendering methods, static generation and server-side rendering.
  2. Page-based routing system, routing zero configuration
  3. Automatic code splitting. Optimize page loading speed.
  4. Support static export, you can export the application as a static website.
  5. Built-in CSS-in-JS library styled-jsx
  6. The solution is mature and can be used in the production environment, and many companies in the world are using it
  7. Application deployment is simple, with its own deployment environment Vercel, and it can also be deployed in other environments.

One, create Next.js project

Created: npm init next-app next-guide
Run: npm run dev
Access: localhost:3000
temporary installation create-next- appused to create the Next.jsproject.

2. Page-based routing system

1. Create a page

In Next.js, pages are React components placed in the pages folder.
Components need to be exported by default.
React does not need to be included in the component file.

pages/list.js

export default function List () {
    
    
  return (
    <div>List Page</div>
  )
}

The access address is: the http://localhost:3000/list
page address corresponds to the file address.

2. Page Jump

By default, the Link component uses JavaScript to jump to the page. That is, the jump in the form of SPA.
If JavaScript is disabled in the browser, use the link to jump. The
Link component should not add attributes other than the href attribute, and the remaining attributes are added to the a tag Above. The
Link component automatically optimizes the application for best performance through the prefetch (in production) function.

import Link from 'next/link'

export default function Home() {
    
    
  return <div>
    Index Page works
    <Link href="/list"><a>Jump to List Page</a></Link>
  </div>
}

Three, static resources, metadata and CSS

1. Static resources

The public folder in the application root directory is used to provide static resources.

Access through the following forms:

public/images/1.jpg -> /images/1.jpg
public/css/base.css -> /css/base.css

2. Modify page metadata

Modify metadata through the Head component

import Head from 'next/head'

<>
  <Head>
    <title>next app</title>
  </Head>
</>

3. CSS style

3.1 Built-in styled-jsx

Styled-jsx is built in Next.js, which is a CSS-in-JS library that allows you to write CSS in React components, and CSS only works inside the components.

export default function Home() {
    
    
  return <>
    <Head>
      <title>Index Page</title>
    </Head>
    <div>
      Index Page works
      <Link href="/list"><a className="demo">Jump to List Page</a></Link>
      <img src="/images/1.jpeg" height="100" />
    </div>
    <style jsx>{
    
    `
      .demo {
        color: red
      }
    `}</style>
  </>
}
3.2 CSS module

By using the CSS module function, it is allowed to write the CSS style of the component in a separate CSS file. The
CSS module convention style file name must be"组件文件名称.module.css"

pages/list.js

import Head from "next/head";
import style from './list.module.css'

export default function List () {
    
    
  return (
    <>
      <Head>
        <title>List Page</title>
      </Head>
      <div className={
    
    style.demo}>List Page</div>
    </>
  )
}

page/list.module.css

.demo {
    
    
  color: green;
  font-size: xx-large;
}
3.3 Global style file
  1. New pages folder in the _app.jsfile and add the following code
  2. Create a styles folder in the project root directory and create global.css in it
  3. In _app.js, import global.css through import.
  4. Restart the development server

pages/_app.js

import '../styles/globals.css'

function MyApp({
    
     Component, pageProps }) {
    
    
  return <Component {
    
    ...pageProps} />
}

export default MyApp

styles/globals.css

html,
body {
    
    
  padding: 0;
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen,
    Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
  background: tomato;
}

a {
    
    
  color: inherit;
  text-decoration: none;
}

* {
    
    
  box-sizing: border-box;
}

Fourth, pre-rendering

1. Overview of pre-rendering

Pre-rendering means that the splicing of data and HTML is completed in advance on the server side.
Pre-rendering can make SEO more friendly.
Pre-rendering will bring a better user experience, you can view the application UI without running JavaScript.

2. Two forms of pre-rendering

Two forms of pre-rendering are supported in Next.js: static generation and server-side rendering.
Static generation and server-side rendering are at different timings for generating HTML.
Static generation: Static generation is to generate HTML at build time. Every subsequent request will share the HTML generated during the build.
Server-side rendering: Server-side rendering is to generate HTML when requested. Every request will regenerate HTML.

3. Choice of two pre-rendering methods

Next.js allows developers to choose different pre-rendering methods for each page. Different pre-rendering methods have different characteristics and should be rendered according to the scene.
But it is recommended that most pages use static generation.
Static generation is built once and used repeatedly, and the access speed is fast, because the pages are generated in advance.
Applicable scenarios: marketing pages, blog posts, e-commerce product lists, help and documentation.
The server-side rendering access speed is not as fast as static generation, but since each request is re-rendered, it is suitable for pages with frequently updated data or pages whose content changes with the request.

4. Static generation without data and with data

If the component does not need to obtain data from other places, it is directly generated statically.
If the component needs to obtain data from other places, Next.js will obtain the data required by the component in advance during construction, and then generate the component statically.

5. Generate getStaticProps statically

The function of the getStaticProps method is to obtain the data required for static generation of the component. And pass the data to the component through props.
This method is an asynchronous function and needs to be exported inside the component.
In development mode, getStaticProps is changed to run on every request.
In production mode, getStaticProps will only be executed at build time, and the getStaticProps method will not be executed every time the /list page is accessed.

pages/list.js

import Head from "next/head";
import style from './list.module.css'
import {
    
     readFile } from "fs";
import {
    
     promisify } from "util";
import {
    
     join } from "path";

const read = promisify(readFile)

export default function List ({
    
    data}) {
    
    
  return (
    <>
      <Head>
        <title>List Page</title>
      </Head>
      <div className={
    
    style.demo}>List Page</div>
      <div>{
    
    data}</div>
    </>
  )
}

export async function getStaticProps () {
    
    
  let data = await read(join(process.cwd(), 'pages', '_app.js'), 'utf-8')
  console.log(data) // 会在 node 环境下输出,这个函数会在构建时运行
  return {
    
    
    props: {
    
    
      data
    }
  }
}

6. Server-side rendering getServerSideProps

If you use server-side rendering, you need to export the getServerSideProps method in the component

Change the getStaticProps method in list.js to getServerSideProps method, where getServerSideProps also has a parameter of context.

The getServerSideProps method is not executed in development mode.

In production mode:
Run to npm run buildgenerate the .next folder, you can see that the list page will not generate an HTML page.
Then run npm startthe code that starts the production environment, visit the /list page, and the node console will output the print statement in the getServerSideProps method.
Because getServerSideProps is used, it means that server-side rendering is used instead of static generation, so the getServerSideProps method will be executed for each visit.

6. Static generation based on dynamic routing

  1. Generate HTML pages for page components based on parameters, and generate as many HTML pages as there are parameters
  2. When building an application, first get all the routing parameters that users can access, then get specific data based on the routing parameters, and then generate static HTML based on the data.

7. Realize static generation based on dynamic routing

  1. Create a page component file based on dynamic routing, add [] outside the file name when naming it, such as [id].js
  2. Export the asynchronous function getStaticPaths, which is used to obtain the routing parameters that all users can access
export async function getStaticPaths () {
    
    
  // 此处获取所有用户可以访问的路由参数
  return {
    
    
    // 返回固定合适的路由参数
    paths: [{
    
    params: {
    
    id: 1}}, {
    
    params: {
    
    id: 2}}],
    // 当用户访问的路由有参数没有在当前函数中返回时,是否显示 404 页面, false 表示显示, true 表示不显示
    fallback: false
  }
}
  1. Export the asynchronous function getStaticProps, which is used to obtain specific data based on routing parameters
export async function getStaticProps ({
    
    params}) {
    
    
  // params -> {id: 1}
  // 此处根据路由参数获取具体数据
  return {
    
    
    // 将数据传递到组件中进行静态页面的生成
    props: {
    
    }
  }
}

Note: getStaticPaths and getStaticProps only run on the server side, never run on the client side, or even packaged into the client side JavaScript, which means that you can write server-side code at will, such as querying the database.

8. Custom 404 page

To create a custom 404 page, you need to create a 404.js file in the pages folder

export default function Error () {
    
    
  return <div>404 ~</div>
}

五、API Routes

1. How to implement API Routes

  1. Create an API Routes file in the pages/api folder. Such as user.js
  2. The request processing function is exported by default in the file, the function has two parameters, req is the request object, res is the response object
export default function (req, res) {
    
    
  res.status(200).send({
    
    id: 1, name: 'TOM'})
}

Note: Currently API Routes can accept any Http request method.

  1. Access API Routes: localhost:3000/api/user
    Do not access API Routes in the getStaticPaths or getStaticProps function, because these two functions are running on the server side, you can write server-side code directly.

Six, movie project

1. Create a project

npm init next-app movie
cd movie
npm i @chakra-ui/react @emotion/react @emotion/styled framer-motion
npm install react-icons
npm install @emotion/babel-preset-css-prop -D
npm install @babel/core
npm run dev

Visit: localhost:3000

pages/_app.js

// import '../styles/globals.css'

import {
    
     ChakraProvider } from '@chakra-ui/react'
import theme from '@chakra-ui/theme'

function MyApp({
    
     Component, pageProps }) {
    
    
  return <ChakraProvider theme={
    
    theme}>
    <Component {
    
    ...pageProps} />
  </ChakraProvider>
}

export default MyApp

2. Start the data service

npm install
npm run dev

Data service address IP: localhost:3005

Export in the axiosConfig.js file baseURL = 'http://localhost:3005'

3. Write the code

4. Generate static files

npm run export
serve out

Visit: localhost:5000

5. Customize next service

package.json

    "mydev": "nodemon server/index.js",

server/index.js

const express = require('express')
const next = require('next')

const dev = process.env.NODE_ENV !== 'production'

const app = next({
    
    dev})

const handler = app.getRequestHandler()

// prepare 方法是准备一下 next 应用
app.prepare().then(() => {
    
    
  const server = express()

  server.get('/hello', (req, res) => {
    
    
     res.send('Hello Next.js')
  })

  server.get('*', (req, res) => {
    
    
    handler(req, res)
  })

  server.listen(3000, () => console.log('服务器启动成功,请访问: http://localhost:3000'))
})

6. Deploy to Vercel

I first deployed the data service to my server, the address is http://jiailing.com:3005, this address should be written in the axiosConfig.js file, and give the baseURL variable.

Then create a repository on GitHub and import the project code into the GitHub repository. Then log in to https://vercel.com/ and select this GitHub repository for deployment.

Guess you like

Origin blog.csdn.net/jal517486222/article/details/112798540