next从入门到实战_Next.js入门

next从入门到实战

介绍 (Introduction)

Working on a modern JavaScript application powered by React is awesome until you realize that there are a couple problems related to rendering all the content on the client-side.

直到您意识到存在与在客户端呈现所有内容有关的几个问题之前,在React所支持的现代JavaScript应用程序上的工作很棒。

First, the page takes longer to the become visible to the user, because before the content loads, all the JavaScript must load, and your application needs to run to determine what to show on the page.

首先,页面花了更长的时间才对用户可见,因为在加载内容之前,必须加载所有JavaScript,并且您的应用程序需要运行才能确定在页面上显示的内容。

Second, if you are building a publicly available website, you have a content SEO issue. Search engines are getting better at running and indexing JavaScript apps, but it’s much better if we can send them content instead of letting them figure it out.

其次,如果您要建立一个公开可用的网站,则存在内容SEO问题。 搜索引擎在运行和索引JavaScript应用方面越来越好,但是如果我们可以向他们发送内容而不是让他们弄清楚,那就更好了。

The solution to both of those problems is server rendering, also called static pre-rendering.

解决这两个问题的方法是服务器渲染 ,也称为静态预渲染

Next.js is one React framework to do all of this in a very simple way, but it’s not limited to this. It’s advertised by its creators as a zero-configuration, single-command toolchain for React apps.

Next.js是一个React框架,可以通过非常简单的方式完成所有这些操作,但不仅限于此。 它的创建者宣传它是React应用程序零配置单命令工具链

It provides a common structure that allows you to easily build a frontend React application, and transparently handle server-side rendering for you.

它提供了一种通用结构,可让您轻松构建前端React应用程序,并为您透明地处理服务器端渲染。

主要特点 (Main features)

Here is a non-exhaustive list of the main Next.js features:

这是Next.js主要功能的详尽列表:

  • Hot Code Reloading: Next.js reloads the page when it detects any change saved to disk.

    Hot Code Reloading:当Next.js检测到任何保存到磁盘的更改时,就会重新加载页面。

  • Automatic Routing: any URL is mapped to the filesystem, to files put in the pages folder, and you don’t need any configuration (you have customization options of course).

    自动路由 :任何URL都映射到文件系统, pages文件夹中的文件,并且您不需要任何配置(当然,您可以使用自定义选项)。

  • Single File Components: using styled-jsx, completely integrated as built by the same team, it’s trivial to add styles scoped to the component.

    单个文件组件 :使用styled-jsx ,完全由同一团队构建而成 ,集成在一起,添加范围限定于该组件的样式很简单。

  • Server Rendering: you can (optionally) render React components on the server side, before sending the HTML to the client.

    服务器渲染 :您可以(可选)在将HTML发送到客户端之前在服务器端渲染React组件。

  • Ecosystem Compatibility: Next.js plays well with the rest of the JavaScript, Node and React ecosystem.

    生态系统兼容性 :Next.js与其余JavaScript,Node和React生态系统兼容

  • Automatic Code Splitting: pages are rendered with just the libraries and JavaScript that they need, no more.

    自动代码拆分 :仅使用所需的库和JavaScript呈现页面,而不再需要。

  • Prefetching: the Link component, used to link together different pages, supports a prefetch prop which automatically prefetches page resources (including code missing due to code splitting) in the background.

    预取 :用于将不同页面链接在一起的Link组件支持prefetch道具,该道具可在后台自动预取页面资源(包括由于代码拆分而丢失的代码)。

  • Dynamic Components: you can import JavaScript modules and React Components dynamically (https://github.com/zeit/next.js#dynamic-import).

    动态组件 :您可以动态导入JavaScript模块和React组件( https://github.com/zeit/next.js#dynamic-import )。

  • Static Exports: using the next export command, Next.js allows you to export a fully static site from your app.

    静态导出 :使用next export命令,Next.js允许您从应用程序导出完全静态的网站。

安装 (Installation)

Next.js supports all the major platforms: Linux, macOS, Windows.

Next.js支持所有主要平台:Linux,macOS,Windows。

A Next.js project is started easily with npm:

使用npm可以轻松启动Next.js项目:

npm install next react react-dom

入门 (Getting started)

Create a package.json file with this content:

创建具有以下内容的package.json文件:

{
  "scripts": {
    "dev": "next"
  }
}

If you run this command now:

如果立即运行此命令:

npm run dev

the script will raise an error complaining about not finding the pages folder. This is the only thing that Next.js requires to run.

该脚本将抱怨找不到pages文件夹,从而引发错误。 这是Next.js唯一需要运行的东西。

Create an empty pages folder, and run the command again, and Next.js will start up a server on localhost:3000.

创建一个空pages文件夹,然后再次运行命令,Next.js将在localhost:3000上启动服务器。

If you go to that URL now, you’ll be greeted by a friendly 404 page, with a nice clean design.

如果您现在转到该URL,则会看到一个友好的404页面,它的外观简洁漂亮。

A 404 page returned by Next.js

Next.js handles other error types as well, like 500 errors for example.

Next.js也处理其他错误类型,例如500个错误。

创建一个页面 (Create a page)

In the pages folder create an index.js file with a simple React functional component:

pages文件夹中创建一个带有简单React功能组件的index.js文件:

export default () => (
  <div>
    <p>Hello World!</p>
  </div>
)

If you visit localhost:3000, this component will automatically be rendered.

如果您访问localhost:3000 ,则将自动呈现此组件。

Why is this so simple?

为什么这么简单?

Next.js uses a declarative pages structure, which is based on the filesystem structure.

Next.js使用基于文件系统结构的声明性页面结构。

Pages are inside a pages folder, and the page URL is determined by the page file name. The filesystem is the pages API.

页面位于pages文件夹内,页面URL由页面文件名确定。 文件系统是页面API。

服务器端渲染 (Server-side rendering)

Open the page source, View -> Developer -> View Source with Chrome.

打开页面源,然后View -> Developer -> View Source使用Chrome View -> Developer -> View Source

As you can see, the HTML generated by the component is sent directly in the page source. It’s not rendered client-side, but instead it’s rendered on the server.

如您所见,组件生成HTML直接在页面源中发送。 它不是在客户端呈现的,而是在服务器上呈现的。

The Next.js team wanted to create a developer experience for server rendered pages similar to the one you get when creating a basic PHP project, for example, where you drop PHP files and you call them, and they show up as pages. Internally of course it’s all very different, but the apparent ease of use is clear.

Next.js团队希望为服务器呈现的页面创建开发人员体验,类似于创建基本PHP项目时获得的页面,例如,在其中放置PHP文件并对其进行调用,然后将它们显示为页面。 在内部,这当然是非常不同的,但是明显的易用性显而易见。

添加第二页 (Add a second page)

Let’s create another page, in pages/contact.js

让我们在pages/contact.js创建另一个页面

export default () => (
  <div>
    <p>
      <a href='mailto:my@email.com'>Contact us!</a>
    </p>
  </div>
)

If you point your browser to localhost:3000/contact this page will be rendered. As you can see, also this page is server rendered.

如果将浏览器指向localhost:3000/contact则将显示此页面。 如您所见,此页面也是服务器呈现的。

热装 (Hot reloading)

Note how you did not have to restart the npm process to load the second page. Next.js does this for you under the hood.

请注意,您不必重新启动npm进程即可加载第二页。 Next.js在后台为您完成此任务。

客户端渲染 (Client rendering)

Server rendering is very convenient in your first page load, for all the reasons we saw above, but when it comes to navigating inside the website, client-side rendering is key to speeding up the page load and improving the user experience.

由于上面提到的所有原因,服务器呈现在第一次加载页面时非常方便,但是在网站内部导航时,客户端呈现是加快页面加载和改善用户体验的关键。

Next.js provides a Link component you can use to build links. Try linking the two pages above.

Next.js提供了可用于构建链接的Link组件。 尝试链接上面的两个页面。

Change index.js to this code:

index.js更改为以下代码:

import Link from 'next/link'

export default () => (
  <div>
    <p>Hello World!</p>
    <Link href='/contact'>
      <a>Contact me!</a>
    </Link>
  </div>
)

Now go back to the browser and try this link. As you can see, the Contact page loads immediately, without a page refresh.

现在返回浏览器并尝试此链接。 如您所见,“联系人”页面将立即加载,而不会刷新页面。

This is client-side navigation working correctly, with complete support for the History API, which means your users back button won’t break.

这是客户端导航正常工作,并且完全支持History API ,这意味着您的用户后退按钮不会损坏。

If you now cmd-click the link, the same Contact page will open in a new tab, now server rendered.

如果现在按cmd-click链接,则将在新选项卡中打开同一“联系人”页面,现在服务器已呈现。

动态页面 (Dynamic pages)

A good use case for Next.js is a blog, as it’s something that all developers know how it works, and it’s a good fit for a simple example of how to handle dynamic pages.

Next.js的一个很好的用例是一个博客,因为它是所有开发人员都知道的工作原理,并且非常适合作为一个如何处理动态页面的简单示例。

A dynamic page is a page that has no fixed content, but instead display some data based on some parameters.

动态页面是没有固定内容,而是根据某些参数显示一些数据的页面。

Change index.js to

index.js更改为

import Link from 'next/link'

const Post = (props) => (
  <li>
    <Link href={`/post?title=${props.title}`}>
      <a>{props.title}</a>
    </Link>
  </li>
)

export default () => (
  <div>
    <h2>My blog</h2>
    <ul>
      <li>
        <Post title='Yet another post' />
        <Post title='Second post' />
        <Post title='Hello, world!' />
      </li>
    </ul>
  </div>
)

This will create a series of posts and will fill the title query parameter with the post title:

这将创建一系列帖子,并用帖子标题填充title查询参数:

The posts list

Now create a post.js file in the pages folder, and add:

现在在pages文件夹中创建一个post.js文件,并添加:

export default (props) => <h1>{props.url.query.title}</h1>

Now clicking a single post will render the post title in a h1 tag:

现在单击单个帖子将在h1标签中呈现帖子标题:

A single post

You can use clean URLs without query parameters. The Next.js Link component helps us by accepting an as attribute, which you can use to pass a slug:

您可以使用不带查询参数的干净URL。 Next.js链接组件通过接受as属性来帮助我们,您可以使用它传递一个子弹:

import Link from 'next/link'

const Post = (props) => (
  <li>
    <Link as={`/${props.slug}`} href={`/post?title=${props.title}`}>
      <a>{props.title}</a>
    </Link>
  </li>
)

export default () => (
  <div>
    <h2>My blog</h2>
    <ul>
      <li>
        <Post slug='yet-another-post' title='Yet another post' />
        <Post slug='second-post' title='Second post' />
        <Post slug='hello-world' title='Hello, world!' />
      </li>
    </ul>
  </div>
)

CSS-in-JS (CSS-in-JS)

Next.js by default provides support for styled-jsx, which is a CSS-in-JS solution provided by the same development team, but you can use whatever library you prefer, like Styled Components.

默认情况下,Next.js提供对styled-jsx的支持,这是同一开发团队提供CSS-in-JS解决方案,但是您可以使用喜欢的任何库,例如Styled Components

Example:

例:

export default () => (
  <div>
    <p>
      <a href='mailto:my@email.com'>Contact us!</a>
    </p>
    <style jsx>{`
      p {
        font-family: 'Courier New';
      }
      a {
        text-decoration: none;
        color: black;
      }
      a:hover {
        opacity: 0.8;
      }
    `}</style>
  </div>
)

Styles are scoped to the component, but you can also edit global styles adding global to the style element:

样式是组件的作用域,但是您也可以编辑全局样式,将global添加到style元素中:

export default () => (
  <div>
    <p>
      <a href='mailto:my@email.com'>Contact us!</a>
    </p>
    <style jsx global>{`
      body {
        font-family: 'Benton Sans', 'Helvetica Neue';
        margin: 2em;
      }
      h2 {
        font-style: italic;
        color: #373fff;
      }
    `}</style>
  </div>
)

导出静态站点 (Exporting a static site)

A Next.js application can be easily exported as a static site, which can be deployed on one of the super fast static site hosts, like Netlify or Firebase Hosting, without the need to set up a Node environment.

Next.js应用程序可以轻松导出为静态站点,可以将其部署在NetlifyFirebase Hosting等超快速静态站点主机之一上,而无需设置Node环境。

The process requires you to declare the URLs that compose the site, but it’s a straightforward process.

该过程要求您声明组成网站的URL,但这是一个简单的过程

部署中 (Deploying)

Creating a production-ready copy of the application, without source maps or other development tooling that aren’t needed in the final build, is easy.

无需最终版本中不需要的源映射或其他开发工具,即可轻松地创建应用程序的生产就绪副本。

At the beginning of this tutorial you created a package.json file with this content:

在本教程的开头,您创建了一个具有以下内容的package.json文件:

{
  "scripts": {
    "dev": "next"
  }
}

which was the way to start up a development server using npm run dev.

这是使用npm run dev启动开发服务器的方法。

Now just add the following content to package.json instead:

现在,只需将以下内容添加到package.json

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

and prepare your app by running npm run build and npm run start.

并通过运行npm run buildnpm run start准备您的应用程序。

现在 (Now)

Zeit is now called Vercel, and this tutorial might be outdated

Zeit现在称为Vercel ,并且本教程可能已过时

The company behind Next.js provides an awesome hosting service for Node.js applications, called Now.

Next.js背后的公司为Node.js应用程序提供了很棒的托管服务,称为Now

Of course they integrate both their products so you can deploy Next.js apps seamlessly, once you have Now installed, by running the now command in the application folder.

当然,他们集成了这两个产品,因此, 一旦安装Now ,就可以通过在application文件夹中运行now命令来无缝部署Next.js应用程序。

Behind the scenes Now sets up a server for you, and you don’t need to worry about anything, just wait for your application URL to be ready.

幕后现在为您设置服务器,您无需担心任何事情,只需等待应用程序URL就绪即可。

区域 (Zones)

You can set up multiple Next.js instances to listen to different URLs, yet the application to an outside user will look like it’s being powered by a single server: https://github.com/zeit/next.js/#multi-zones

您可以设置多个Next.js实例来侦听不同的URL,但是外部用户的应用程序看起来像是由一台服务器提供动力: https : //github.com/zeit/next.js/#multi-区域

外挂程式 (Plugins)

Next.js has a list of plugins at https://github.com/zeit/next-plugins

Next.js的插件列表位于https://github.com/zeit/next-plugins

小故障入门套件 (Starter kit on Glitch)

If you’re looking to experiment, I recommend Glitch. Check out my Next.js Glitch Starter Kit.

如果您想尝试,建议您使用Glitch。 查看我的Next.js Glitch入门工具包

进一步了解Next.js (Read more on Next.js)

I can’t possibly describe every feature of this great framework, and the main place to read more about Next.js is the project readme on GitHub.

我无法描述这个出色框架的每个功能,而更多了解Next.js的主要地方是GitHub上的项目自述文件

翻译自: https://flaviocopes.com/nextjs/

next从入门到实战

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值