react 服务端渲染框架



Next.js | react server side rendering Framework : As we all know that react is a very popular ui library for creating blazing fast web apps and even mobile apps .

Next.js | react服务器端渲染框架:众所周知,react是一个非常流行的ui库,用于创建快速的Web应用程序甚至移动应用程序。

(The Benefits of Server-Side Rendering)

SEO might be the conversation that starts your team talking about server-side rendering, but it’s not the only potential benefit.

SEO可能是使您的团队开始谈论服务器端渲染的对话,但这并不是唯一的潜在好处。

Here’s the big one: server-side rendering displays pages faster. With server-side rendering, your server’s response to the browser is the HTML of your page that is ready to be rendered so the browser can start rendering without having to wait for all the JavaScript to be downloaded and executed. There’s no “white page” while the browser downloads and executes the JavaScript and other assets needed to render the page, which is what might happen in an entirely client-rendered React site.

这是最大的问题: 服务器端渲染可以更快地显示页面 。 通过服务器端渲染,服务器对浏览器的响应就是页面上准备渲染HTML,因此浏览器可以开始渲染,而不必等待所有JavaScript都被下载和执行。 当浏览器下载并执行呈现页面所需JavaScript和其他资源时,没有“白页”,这是在完全由客户端呈现的React网站中可能发生的情况。

And Next js is a perfect solution for creating react app which are rich in server side rendring capabilities .

而Next js是创建具有丰富服务器端渲染功能的react应用的理想解决方案。

In this article we will see some great stuff in nextjs

在本文中,我们将在nextjs中看到一些很棒的东西

For this article we will first create a nextjs starter project

对于本文,我们将首先创建一个nextjs入门项目

npx create-next-app sampleapp

now in the pages directory you will have index.js file which will serve as home route for your application and if you want more routes you can just create files and use them as route

现在在pages目录中,您将拥有index.js文件,该文件将用作您的应用程序的本地路由,如果您需要更多路由,则可以创建文件并将其用作路由

  1. pages/index.js → localhost:3000
  2. pages/about.js → localhost:3000/about

(Special Pages)

The first one is pages/_document.js, which allows us to define the surroundings of the page, such as the section. This could be useful to change the page title, add meta information or styles, and so on

第一个是pages / _document.js,它使我们能够定义页面的周围环境,例如部分。 这对于更改页面标题,添加元信息或样式等很有用。

// pages/_document.js
import Document, {Head, Main, NextScript} from 'next/document';
export default class MyDocument extends Document {
    render() {
        return (
            <html>
            <Head>
                <title>Smart Next Js</title>
                // Enter Link Tags and scripts tags
            </Head>
            <body>
            <Main/>
            <NextScript/>
            </body>
            </html>
        )
    }
}

we’ve configured the very basic surroundings of the actual markup that will be injected in the page straight in the body tag; also, we’ve added a title to the custom Head component.

我们已经配置了实际标记的基本环境,这些标记将直接插入到body标签中的页面中; 此外,我们还为自定义Head组件添加了标题。

The next special Page is pages/_app.js, which allows us to wrap all pages (including the error) in a special wrapper

下一个特殊页面是pages / _app.js,它使我们可以将所有页面(包括错误)包装在特殊包装器中

// pages/_app.js
import App, {Container} from 'next/app';
import React from 'react';
export default class MyApp extends App {
  static async getInitialProps ({ Component, router, ctx }) {
    let pageProps = {};
    if (Component.getInitialProps) pageProps = await Component.getInitialProps(ctx);
    return {pageProps};
  }
  state = {someState: ''};
  render () {
    const {Component, pageProps} = this.props
    return (<Container>
      <Component {...pageProps} someState={this.state.someState}/>
    </Container>);
  }
}

The next one is the default 404 or 500 error handler, pages/_error.js

下一个是默认的404或500错误处理程序,pages / _error.js

// pages/_error.js
import React from 'react'
export default class Error extends React.Component {
  static getInitialProps({ res, err }) {
    const statusCode = res ? res.statusCode : err ? err.statusCode : null;
    return { statusCode }
  }
  render() {
    return (
      <p>
        {this.props.statusCode
          ? `An error ${this.props.statusCode} occurred on server`
          : 'An error occurred on client'}
      </p>
    )
  }
}

(Configuration (use scss in next js))

Lets add the scss support in our nextjs app

让我们在nextjs应用程序中添加对scss的支持

lets create a scss file for style in src/index.scss

让我们在src / index.scss中创建样式的scss文件

body
  font-family: Arial, sans-serif
  font-size: 12px

Lets import this file in pages/_app.js (assuming this is a global stylesheet file if not you can import it in the specific pages also )

让我们将此文件导入pages / _app.js中(假设这是一个全局样式表文件,如果没有,您也可以将其导入到特定页面中)

and if you run

如果你跑

you will get en error

你会得到错误

to resolve it we will first need some npm pacakages

为了解决这个问题,我们首先需要一些npm pacakages

npm install next node-sass @zeit/next-sass --save-dev

next create a file named next.config.js in the route of your app

接下来在您的应用程序路由中创建一个名为next.config.js的文件

// next.config.js
const withSass = require('@zeit/next-sass')
module.exports = withSass()

and with this changes you should be able to run your application with scss support

通过此更改,您应该能够在scss支持下运行您的应用程序

Another useful thing is the configuration of the build/dev phases via custom config.

另一个有用的事情是通过自定义配置来配置构建/开发阶段。

To do that, you can use the following template:

为此,您可以使用以下模板:

// next.config.js
const withSass = require('@zeit/next-sass');
const {PHASE_DEVELOPMENT_SERVER} = require('next/constants');
module.exports = (phase, {defaultConfig}) => {
    if(phase === PHASE_DEVELOPMENT_SERVER) {
        return withSass(defaultConfig);
    }
    return withSass(Object.assign({}, defaultConfig, {
        distDir: 'build-new'
    }));
};

Here, we have set the destination directory to build-new. The function receives phase and the defaultConfig as arguments, and you can use phase to determine what has to be modified in defaultConfig, based on your preferences.

在这里,我们将目标目录设置为新建。 该函数接收阶段和defaultConfig作为参数,并且您可以根据自己的喜好使用阶段来确定在defaultConfig中必须修改的内容。

Here, config also allows us to expose variables to your pages at runtime:

在这里,config还允许我们在运行时向页面公开变量:

// next.config.js
const withSass = require("@zeit/next-sass");
const { PHASE_DEVELOPMENT_SERVER } = require("next/constants");
module.exports = (phase, { defaultConfig: defaultConfig }) => {
  if (phase === PHASE_DEVELOPMENT_SERVER) {
    return withSass(defaultConfig);
  }
  return withSass(
    Object.assign({}, defaultConfig, {
      distDir: "build-custom",
    })
  );
};
module.exports = {
  serverRuntimeConfig: {
    secretKey: "secret", 
  },
  publicRuntimeConfig: {
    publicKey: "public", 
  },
};

(Extend Webpack (use typescript in next js))

(Without next js Plugin)

Webpack is the bundler used to produce the Next.js dev server and builds. It can be configured to bundle more things than by default. As an example, let’s add TypeScript.

Webpack是用于生产Next.js开发服务器和构建程序的捆绑程序。 它可以配置为捆绑更多的东西,而不是默认情况。 作为示例,让我们添加TypeScript。

Lets start by creating tsconfig file in the root

让我们从在根目录中创建tsconfig文件开始

tsconfig.json:
{
  "compileOnSave": false,
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "baseUrl": ".",
    "jsx": "preserve",
    "lib": [
      "dom",
      "es2015",
      "es2016"
    ],
    "module": "esnext",
    "moduleResolution": "node",
    "sourceMap": true,
    "skipLibCheck": true,
    "target": "esnext",
    "typeRoots": [
      "./node_modules/@types"
    ]
  }
}

Next lets add some dependencies for type script

接下来让我们为类型脚本添加一些依赖

npm install ts-loader typescript @types/react 
@types/next @types/node --save-dev

make change in the next.config.js

在next.config.js中进行更改

// next.config.js
const withSass = require("@zeit/next-sass");
const { PHASE_DEVELOPMENT_SERVER } = require("next/constants");
module.exports = (phase, { defaultConfig: defaultConfig }) => {
  if (phase === PHASE_DEVELOPMENT_SERVER) {
    return withSass(defaultConfig);
  }
  return withSass(
    Object.assign({}, defaultConfig, {
      distDir: "build-custom",
    })
  );
};
module.exports = {
  webpack(config, { dir, defaultLoaders }) {
    config.module.rules.push({
      // add a custom loader rule
      test: /\.+(ts|tsx)$/, // apply this rule only to TS[X] files
      use: [
        defaultLoaders.babel, // we use default babel on top of TS
        {
          loader: "ts-loader",
          options: { transpileOnly: true },
        },
      ],
      include: [dir],
      exclude: /node_modules/, // exclude everything from node_modules for performance
    });
    config.resolve.extensions.push(".ts", ".tsx"); // register require resolve extensions
    return config;
  },
};
module.exports = {
  serverRuntimeConfig: {
    serverOnly: "secret", 
  },
  publicRuntimeConfig: {
    serverAndClient: "public",
  },
};

thats it just change index.js to index.tsx and everything should be up and running with typescript now

就是这样,只需将index.js更改为index.tsx,一切都应该已经启动并使用typescript运行了

(With Next js Plugin)

now as typescript is so popular next already has a plugin for it just install this dependencies

现在,因为打字稿非常受欢迎,接下来已经有一个插件可以安装此依赖项

npm install @zeit/next-typescript @types/react @types/next
@types/node --save-dev

add in next.config.js

添加next.config.js

// for typescript 
const withTypescript = require('@zeit/next-typescript');
module.exports = withTypescript({});

The final next.config.js will look like this

最终的next.config.js将如下所示

// next.config.js
const withSass = require("@zeit/next-sass");
const { PHASE_DEVELOPMENT_SERVER } = require("next/constants");
// for typescript 
const withTypescript = require('@zeit/next-typescript');
module.exports = withTypescript({});
module.exports = (phase, { defaultConfig: defaultConfig }) => {
  if (phase === PHASE_DEVELOPMENT_SERVER) {
    return withSass(defaultConfig);
  }
  return withSass(
    Object.assign({}, defaultConfig, {
      distDir: "build-custom",
    })
  );
};
module.exports = {
  serverRuntimeConfig: {
    serverOnly: "secret", 
  },
  publicRuntimeConfig: {
    serverAndClient: "public", 
  },
};

if this is helpful do share it with the community it motivates to write more

如果这有帮助,请与社区分享,以鼓励编写更多内容

Thanks

谢谢

Originally published at https://blog.smartcodehub.com on August 2, 2020.

最初于 2020年8月2日 发布在 https://blog.smartcodehub.com 。



翻译自: https://medium.com/swlh/next-js-react-server-side-rendering-framework-5d8b72cb9642

react 服务端渲染框架