Next.js 入门

欢迎关注个人公众号睿Talk,获取我最新的文章:
clipboard.pngjavascript

1、前言

当使用 React 开发系统的时候,经常须要配置不少繁琐的参数,如 Webpack 配置、Router 配置和服务器配置等。若是须要作 SEO,要考虑的事情就更多了,怎么让服务端渲染和客户端渲染保持一致是一件很麻烦的事情,须要引入不少第三方库。针对这些问题,Next.js提供了一个很好的解决方案,使开发人员能够将精力放在业务上,从繁琐的配置中解放出来。下面咱们一块儿来看看它的一些特性。前端

2、特性介绍

Next.js 具备如下几点特性:java

  • 默认支持服务端渲染
  • 自动根据页面进行代码分割
  • 简洁的客户端路由方案(基于页面)
  • 基于 Webpack 的开发环境,支持热模块替换
  • 能够跟 Express 或者其它 Node.js 服务器完美集成
  • 支持 Babel 和 Webpack 的配置项定制

3、Hello World

执行如下命令,开始 Next.js 之旅:react

mkdir hello-next
cd hello-next
npm init -y
npm install --save react react-dom next
mkdir pages

package.json中输入如下内容:express

{
  "scripts": {
    "dev": "next",
    "build": "next build",
    "start": "next start"
  }
}

在 pages 文件夹下,新建一个文件 index.jsnpm

const Index = () => (
  <div>
    <p>Hello Next.js</p>
  </div>
)

export default Index

在控制台输入npm run dev,这时候在浏览器输入http://localhost:3000,就能看到效果了。json

clipboard.png

4、路由

Next.js 没有路由配置文件,路由的规则跟 PHP 有点像。只要在 pages 文件夹下建立的文件,都会默认生成以文件名命名的路由。咱们新增一个文件看效果pages/about.jssegmentfault

export default function About() {
  return (
    <div>
      <p>This is the about page</p>
    </div>
  )
}

在浏览器输入http://localhost:3000/about,就能看到相应页面了。api

clipboard.png

若是须要进行页面导航,就要借助next/link组件,将 index.js 改写:浏览器

import Link from 'next/link'

const Index = () => (
  <div>
    <Link href="/about">
      <a>About Page</a>
    </Link>
    <p>Hello Next.js</p>
  </div>
)

export default Index

这时候就能经过点击连接进行导航了。

若是须要给路由传参数,则使用query string的形式:

<Link href="/post?title=hello">
   <a>About Page</a>
 </Link>

取参数的时候,须要借助框架提供的withRouter方法,参数封装在 query 对象中:

import { withRouter } from 'next/router'

const Page = withRouter(props => (
  <h1>{props.router.query.title}</h1>
))

export default Page

若是但愿浏览器地址栏不显示query string,可使用as属性:

<Link as={`/p/${props.id}`} href={`/post?id=${props.id}`}
  <a>{props.title}</a>
</Link>

这时候浏览器会显示这样的url:localhost:3000/p/12345

5、SSR

Next.js 对服务端渲染作了封装,只要遵照一些简单的约定,就能实现 SSR 功能,减小了大量配置服务器的时间。以上面这个 url 为例子,直接在浏览器输入localhost:3000/p/12345是会返回404的,咱们须要本身实现服务端路由处理的逻辑。下面以express为例子进行讲解。新建一个 server.js 文件:

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

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

app
  .prepare()
  .then(() => {
    const server = express()

    // 处理localhost:3000/p/12345路由的代码
    server.get('/p/:id', (req, res) => {
      const actualPage = '/post'
      const queryParams = { title: req.params.id }
      app.render(req, res, actualPage, queryParams)
    })

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

    server.listen(3000, err => {
      if (err) throw err
      console.log('> Ready on http://localhost:3000')
    })
  })
  .catch(ex => {
    console.error(ex.stack)
    process.exit(1)
  })

当遇到/p/:id这种路由的时候,会调用app.render方法渲染页面,其它的路由则调用app.getRequestHandler方法。

不管是服务端渲染仍是客户端渲染,每每都须要发起网络请求获取展现数据。若是要同时考虑 2 种渲染场景,能够用getInitialProps这个方法:

import Layout from '../components/MyLayout.js'
import fetch from 'isomorphic-unfetch'

const Post = props => (
  <Layout>
    <h1>{props.show.name}</h1>
    <p>{props.show.summary.replace(/<[/]?p>/g, '')}</p>
    <img src={props.show.image.medium} />
  </Layout>
)

Post.getInitialProps = async function(context) {
  const { id } = context.query
  const res = await fetch(`https://api.tvmaze.com/shows/${id}`)
  const show = await res.json()

  console.log(`Fetched show: ${show.name}`)

  return { show }
}

export default Post

获取数据后,组件的props就能获取到getInitialProps return 的对象,render 的时候就能直接使用了。getInitialProps是组件的静态方法,不管服务端渲染仍是客户端渲染都会调用。若是须要获取 url 带过来的参数,能够从context.query里面取。

6、CSS in JS

对于页面样式,Next.js 官方推荐使用 CSS in JS 的方式,而且内置了styled-jsx。用法以下:

import Layout from '../components/MyLayout.js'
import Link from 'next/link'

function getPosts() {
  return [
    { id: 'hello-nextjs', title: 'Hello Next.js' },
    { id: 'learn-nextjs', title: 'Learn Next.js is awesome' },
    { id: 'deploy-nextjs', title: 'Deploy apps with ZEIT' }
  ]
}

export default function Blog() {
  return (
    <Layout>
      <h1>My Blog</h1>
      <ul>
        {getPosts().map(post => (
          <li key={post.id}>
            <Link as={`/p/${post.id}`} href={`/post?title=${post.title}`}>
              <a>{post.title}</a>
            </Link>
          </li>
        ))}
      </ul>
      <style jsx>{`
        h1,
        a {
          font-family: 'Arial';
        }

        ul {
          padding: 0;
        }

        li {
          list-style: none;
          margin: 5px 0;
        }

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

        a:hover {
          opacity: 0.6;
        }
      `}</style>
    </Layout>
  )
}

注意<style jsx>后面跟的是模板字符串,而不是直接写样式。

7、导出为静态页面

若是网站都是简单的静态页面,不须要进行网络请求,Next.js 能够将整个网站导出为多个静态页面,不须要进行服务端或客户端动态渲染了。为了实现这个功能,须要在根目录新建一个next.config.js配置文件:

module.exports = {
  exportPathMap: function() {
    return {
      '/': { page: '/' },
      '/about': { page: '/about' },
      '/p/hello-nextjs': { page: '/post', query: { title: 'Hello Next.js' } },
      '/p/learn-nextjs': { page: '/post', query: { title: 'Learn Next.js is awesome' } },
      '/p/deploy-nextjs': { page: '/post', query: { title: 'Deploy apps with Zeit' } }
    }
  }
}

这个配置文件定义了 5 个须要导出的页面,以及这些页面对应的组件和须要接收的参数。而后在package.json定义下面 2 个命令,而后跑一下:

{
  "scripts": {
    "build": "next build",
    "export": "next export"
  }
}

npm run build
npm run export

跑完后根目录就会多出一个out文件夹,全部静态页面都在里面。

clipboard.png

8、组件懒加载

Next.js 默认按照页面路由来分包加载。若是但愿对一些特别大的组件作按需加载时,可使用框架提供的next/dynamic工具函数。

import dynamic from 'next/dynamic'

const Highlight = dynamic(import('react-highlight'))

export default class PostPage extends React.Component {
    renderMarkdown() {
      if (this.props.content) {
        return (
          <div>
            <Highlight innerHTML>{this.props.content}</Highlight>
          </div>
        )
      }

      return (<div> no content </div>);
    }

    render() {
      return (
        <MyLayout>
          <h1>{this.props.title}</h1>
          {this.renderMarkdown()}
        </MyLayout>
      )
    }
  }
}

当 this.props.content 为空的时候,Highlight 组件不会被加载,加速了页面的展示,从而实现按需加载的效果。

9、总结

本文介绍了 Next.js 的一些特性和使用方法。它最大的特色是践行约定大于配置思想,简化了前端开发中一些经常使用功能的配置工做,包括页面路由、SSR 和组件懒加载等,大大提高了开发效率。

更详细的使用介绍请看官方文档

相关文章
相关标签/搜索