positioning

Next. Js is the Node.js full stack framework

  1. css-in-js
  2. Page prerendering + SSR (Server rendering)
  3. Front-end isomorphism (code running at both ends)
  4. Node.js 10.13 and above supports React/Typescript

weaknesses

There is no database-related functionality available for Sequelize or TypeORM, and no test-related functionality available for Jest or Cypress

Create a project

NPM init next-app myAppNameCopy the code

Link Fast Navigation

Usage: put the < a href = 'XXX' > jump < / a > to < Link href = 'XXX' > < a > click jump < / a > < / Link >Copy the code

Advantages page will not refresh, with AJAX request new page content, will not request repeated HTML/CSS/JS, automatically replace content in the page, save the request and parsing, so very fast

Isomorphism code

Log (‘ executed ‘). Both the Node console and the browser console output this statement. Not all code will run

Global configuration

The custom head

You can add global styles to page/_app.js, and introduce head to configure global meta/title and other content

import '.. /styles/globals.css'
import Head from 'next/head'

function MyApp({ Component, pageProps }) {
  return (
    <>
      <Component {. pageProps} / >
      <Head>
        <title>My blog</title>
        <link rel="icon" href="/favicon.ico" />
        <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no, viewport-fit=cover" />
      </Head>
    </>)}export default MyApp

Copy the code

Local CSS

import React from 'react'

export default function X() {
    return (
        <>
            <div>
                <h1>This is the first blog post</h1>
                <hr />
                <a href="/">Back to the home page</a>
            </div>
            <style jsx>
                {`
                h1{
                    color:black;
                }
                `}
            </style>
        </>)}Copy the code

Absolute reference

Create the jsconfig.json file and configure it

"compilerOptions": {
	"baseUrl": "."
}
Copy the code

style.module.css

You can create demo.module. CSS in a style file and use it wherever you want

import React from 'react'
import styles from 'styles/demo.module.css'

export default function X() {
    return (
        <>
        	<div className={styles.wrapper}>I am a wrapper</div>
            <div className={styles.content}>I am content</div>
        </>)}Copy the code

next-images

Suppose we want to use images now, but don’t want to put them in public and reference them directly, and instead reference images from other directories, we can use the plugin to create next. Config first

Module. Exports = withImages({webpack(config, set)) // set withImages = require('next-images') module. Exports = withImages(config, set) option) { return config } })Copy the code

Next.js API

In actual development, we need to request /user/shops apis to return JSON strings. We can create files in the page/ API/directory to return the corresponding data. This code only runs in Node.js

import { NextApiRequest, NextApiResponse } from "next"

export default (req: NextApiRequest, res: NextApiResponse) => {
    res.statusCode = 200
    res.setHeader('Content-Type'.'application/json')
    res.write(JSON.stringify({ name: 'My Name' }))
    res.end()
}
Copy the code

Three renderings in Next

BSR(Client Rendering)

Through the front-end ajax way to obtain data for rendering, this is our common way of rendering, here will not do more to repeat the disadvantages: white screen, SEO is not friendly. Note, however, that it will render twice in Next, once on the back end (to generate HTML), and once on the front end (to bind events to make sure the results are consistent on the back end).

const PostsIndex: NextPage = () = > {
    const [posts, setPosts] = useState<Post[]>([])
    useEffect(() = > {
        axios.get('api/v1/posts').then(res= > {
            setPosts(res.data)
        })
    }, [])
    return (
        <div>
            {posts.map(item => <ul key={item.id}>
                <li>{item.title}</li>
                <li>{item.content}</li>
                <li>{item.date}</li>
            </ul>)}
        </div>)}Copy the code

SSG (Static page generation)

Use getStaticProps to provide the data

Dynamic content is static. The following method generates a static page for the user to download when we package

Next will help us generate HTML (with static content, for direct user access)/ JS (with static content, for quick navigation)/ JSON (with data, for composing new pages with JS) note: the front-end can also get this data, from script

Advantages: No white screen, conducive to SEO.

const PostsIndex: NextPage<Props> = (props) = > {// New HTML content is generated when packaging
    const { posts } = props
    return (
        <div>
            <h1>The article lists</h1>
            {posts.map(item => <p key={item.id}>{item.title}</p>)}
        </div>)}export default PostsIndex;

export const getStaticProps: GetStaticProps = async() = > {// The data will be passed when the package is packaged
    const posts = await getPosts()
    return {
        props: {
            posts
        }
    }
}
Copy the code

Updated SSG Adds routes. Different routes are added according to different content and the page is not refreshed

const PostsShow: NextPage<Props> = (props) = > {
    const { posts } = props
    return (
        <div>The article details<h1>{posts.title}</h1>
            <p>{posts.content}</p>
            <p>{posts.date}</p>
        </div>)}export default PostsShow;

export const getStaticPaths = async() = > {// Define the routing table
    const posts = await getPosts()
    return {
        paths: posts.map(item= > {
            return { params: { id: item.id } }
        }),
        fallback: true}}export const getStaticProps: GetStaticProps = async ({ params }: any) => {
    const id = params.id// Get the routing parameters to get the corresponding parameters
    const posts = await getPostById(id)
    return {
        props: {
            posts
        }
    }
}
Copy the code

SSR (Server rendering)

Use getServerSideProps(content) to re-render on each request, replace the content with the template engine, return the new HTML page service segment rendering (SSR) to solve the white screen problem, SEO problems, can generate user related content (different users show different results)

const Index: NextPage<Props> = (props) = > {
  console.log('props.browser')
  console.log(props.browser)
  return (
    <div>
      <h1>Your browser is :{props. Browser.name}</h1>
    </div>)}export default Index;

export const getServerSideProps: GetServerSideProps = async (ctx) => {
  const ua = ctx.req.headers['user-agent']
  const result = new UAParser(ua)
  console.log(result)
  return {
    props: {
      browser: result.getBrowser()
    }
  }
} 
Copy the code

How to choose the rendering mode