@2fn/dashboard 中文文档教程

发布于 4年前 浏览 29 更新于 3年前

该项目是通过Create Next App 引导的。

此处找到本指南的最新版本. 并查看 Next.js 存储库 以获取最新信息。

Table of Contents

Questions? Feedback?

查看 Next.js FAQ & 文档让我们知道您的反馈。

Folder Structure

创建应用程序后,它应该看起来像:

.
├── README.md
├── components
│   ├── head.js
│   └── nav.js
├── next.config.js
├── node_modules
│   ├── [...]
├── package.json
├── pages
│   └── index.js
├── static
│   └── favicon.ico
└── yarn.lock

Next.js 中的路由是基于文件系统的,所以 ./pages/index.js 映射到 / 路由和 ./pages/about.js 将映射到 /about

./static 目录映射到 next 服务器中的 /static,因此您可以将所有 其他静态资源,例如图像或已编译的 CSS。

开箱即用,我们得到:

  • Automatic transpilation and bundling (with webpack and babel)
  • Hot code reloading
  • Server rendering and indexing of ./pages
  • Static file serving. ./static/ is mapped to /static/

阅读更多关于 Next's Routing

Available Scripts

在项目目录中,您可以运行:

npm run dev

运行应用处于开发模式。
在浏览器中打开http://localhost:3000即可查看。

如果您进行编辑,页面将重新加载。
您还将在控制台中看到任何错误。

npm run build

将用于生产的应用构建到 .next 文件夹。
它在生产模式下正确地捆绑了 React,并优化了构建以获得最佳性能。

npm run start

以生产模式启动应用程序。 应首先使用“next build”编译应用程序。

有关详细信息,请参阅 Next 文档中有关部署 的部分。

Using CSS

styled-jsx 与 next 捆绑在一起,以提供对独立作用域 CSS 的支持。 目的是支持类似于 Web Components 的“shadow CSS”,不幸的是 不支持服务器渲染并且仅支持 JS< /a>。

export default () => (
  <div>
    Hello world
    <p>scoped!</p>
    <style jsx>{`
      p {
        color: blue;
      }
      div {
        background: red;
      }
      @media (max-width: 600px) {
        div {
          background: blue;
        }
      }
    `}</style>
  </div>
)

详细了解 Next 的 CSS 功能

Adding Components

我们建议将 React 组件保存在 ./components 中,它们应该如下所示:

./components/simple.js

const Simple = () => <div>Simple Component</div>

export default Simple // don't forget to export default!

./components/complex.js

import { Component } from 'react'

class Complex extends Component {
  state = {
    text: 'World'
  }

  render() {
    const { text } = this.state
    return <div>Hello {text}</div>
  }
}

export default Complex // don't forget to export default!

Fetching Data

您可以使用 getInitialPropspages 组件中获取数据,如下所示:

./pages/stars.js

const Page = props => <div>Next stars: {props.stars}</div>

Page.getInitialProps = async ({ req }) => {
  const res = await fetch('https://api.github.com/repos/zeit/next.js')
  const json = await res.json()
  const stars = json.stargazers_count
  return { stars }
}

export default Page

对于初始页面加载,getInitialProps 将仅在服务器上执行。 getInitialProps 只会在客户端通过 Link 组件或使用路由 API 导航到不同的路由时执行。

注意:getInitialProps 不能在子组件中使用。 仅在页面中。

阅读有关获取数据的更多信息和组件生命周期

Custom Server

想要使用自定义服务器启动新应用程序吗? 运行 create-next-app --example customer-server custom-app

通常,您使用 next start 启动下一个服务器。 但是,可以以编程方式 100% 启动服务器以自定义路由、使用路由模式等

。此示例使 /a 解析为 ./pages/b,和 /b 解析为 ./pages/a

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, query } = parsedUrl

    if (pathname === '/a') {
      app.render(req, res, '/b', query)
    } else if (pathname === '/b') {
      app.render(req, res, '/a', query)
    } else {
      handle(req, res, parsedUrl)
    }
  }).listen(3000, err => {
    if (err) throw err
    console.log('> Ready on http://localhost:3000')
  })
})

然后,将您的 start 脚本更改为 NODE_ENV=production node server.js< /代码>。

阅读有关自定义服务器和路由

Syntax Highlighting

的更多信息要在您最喜欢的文本编辑器中配置语法突出显示,前往相关的 Babel 文档页面并按照说明进行操作。 涵盖了一些最受欢迎的编辑器。

Deploy to Now

now 提供零配置单命令部署。

  1. 通过推荐的桌面工具或通过带有 npm install 的节点安装 now 命令行工具 - g 现在。

  2. 从您的项目目录运行现在。 您将在输出中看到一个 now.sh URL,如下所示:

    > Ready! https://your-project-dirname-tpspyhtdtk.now.sh (copied to clipboard)
    

    构建完成后将该 URL 粘贴到您的浏览器中,您将看到已部署的应用程序。

您可以在now 此处 找到更多详细信息。

Something Missing?

如果您对我们如何改进本自述文件或一般项目有任何想法,请让我们知道或< a href="https://github.com/segmentio/create-next-app/edit/master/lib/templates/default/README.md">贡献一些!

This project was bootstrapped with Create Next App.

Find the most recent version of this guide at here. And check out Next.js repo for the most up-to-date info.

Table of Contents

Questions? Feedback?

Check out Next.js FAQ & docs or let us know your feedback.

Folder Structure

After creating an app, it should look something like:

.
├── README.md
├── components
│   ├── head.js
│   └── nav.js
├── next.config.js
├── node_modules
│   ├── [...]
├── package.json
├── pages
│   └── index.js
├── static
│   └── favicon.ico
└── yarn.lock

Routing in Next.js is based on the file system, so ./pages/index.js maps to the / route and ./pages/about.js would map to /about.

The ./static directory maps to /static in the next server, so you can put all your other static resources like images or compiled CSS in there.

Out of the box, we get:

  • Automatic transpilation and bundling (with webpack and babel)
  • Hot code reloading
  • Server rendering and indexing of ./pages
  • Static file serving. ./static/ is mapped to /static/

Read more about Next's Routing

Available Scripts

In the project directory, you can run:

npm run dev

Runs the app in the development mode.
Open http://localhost:3000 to view it in the browser.

The page will reload if you make edits.
You will also see any errors in the console.

npm run build

Builds the app for production to the .next folder.
It correctly bundles React in production mode and optimizes the build for the best performance.

npm run start

Starts the application in production mode. The application should be compiled with `next build` first.

See the section in Next docs about deployment for more information.

Using CSS

styled-jsx is bundled with next to provide support for isolated scoped CSS. The aim is to support "shadow CSS" resembling of Web Components, which unfortunately do not support server-rendering and are JS-only.

export default () => (
  <div>
    Hello world
    <p>scoped!</p>
    <style jsx>{`
      p {
        color: blue;
      }
      div {
        background: red;
      }
      @media (max-width: 600px) {
        div {
          background: blue;
        }
      }
    `}</style>
  </div>
)

Read more about Next's CSS features.

Adding Components

We recommend keeping React components in ./components and they should look like:

./components/simple.js

const Simple = () => <div>Simple Component</div>

export default Simple // don't forget to export default!

./components/complex.js

import { Component } from 'react'

class Complex extends Component {
  state = {
    text: 'World'
  }

  render() {
    const { text } = this.state
    return <div>Hello {text}</div>
  }
}

export default Complex // don't forget to export default!

Fetching Data

You can fetch data in pages components using getInitialProps like this:

./pages/stars.js

const Page = props => <div>Next stars: {props.stars}</div>

Page.getInitialProps = async ({ req }) => {
  const res = await fetch('https://api.github.com/repos/zeit/next.js')
  const json = await res.json()
  const stars = json.stargazers_count
  return { stars }
}

export default Page

For the initial page load, getInitialProps will execute on the server only. getInitialProps will only be executed on the client when navigating to a different route via the Link component or using the routing APIs.

Note: getInitialProps can not be used in children components. Only in pages.

Read more about fetching data and the component lifecycle

Custom Server

Want to start a new app with a custom server? Run create-next-app --example customer-server custom-app

Typically you start your next server with next start. It's possible, however, to start a server 100% programmatically in order to customize routes, use route patterns, etc

This example makes /a resolve to ./pages/b, and /b resolve to ./pages/a:

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, query } = parsedUrl

    if (pathname === '/a') {
      app.render(req, res, '/b', query)
    } else if (pathname === '/b') {
      app.render(req, res, '/a', query)
    } else {
      handle(req, res, parsedUrl)
    }
  }).listen(3000, err => {
    if (err) throw err
    console.log('> Ready on http://localhost:3000')
  })
})

Then, change your start script to NODE_ENV=production node server.js.

Read more about custom server and routing

Syntax Highlighting

To configure the syntax highlighting in your favorite text editor, head to the relevant Babel documentation page and follow the instructions. Some of the most popular editors are covered.

Deploy to Now

now offers a zero-configuration single-command deployment.

  1. Install the now command-line tool either via the recommended desktop tool or via node with npm install -g now.

  2. Run now from your project directory. You will see a now.sh URL in your output like this:

    > Ready! https://your-project-dirname-tpspyhtdtk.now.sh (copied to clipboard)
    

    Paste that URL into your browser when the build is complete, and you will see your deployed app.

You can find more details about now here.

Something Missing?

If you have ideas for how we could improve this readme or the project in general, let us know or contribute some!

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文