(SSR) Advantages and disadvantages of server-side rendering

Advantages:

1. The front-end time is low and the first screen loading speed is fast. Because the back end concatenates the HTML, the browser just renders it directly.

2. It’s good for SEO. Because there is a full HTML page on the back end, it is easier for crawlers to crawl and get information, which is better for SEO.

3. Do not occupy client resources. That is, the work of template parsing is completely handed over to the back end, and the client only needs to parse the standard HTML page, which takes less resources for the client, especially for the mobile terminal, and saves more power.

4. Static files are generated on the back-end. Generate cache fragments, which reduces the time wasted on database queries and is very efficient for pages where the data doesn’t change much.

Disadvantages:

1. It is not conducive to the separation of front and rear ends, resulting in low development efficiency. (Before frame)

2. Occupy server resources.

That is, the server parses the HTML template. If there are too many requests, the server will be under certain access pressure. If you use front-end rendering, you split the parsing load on the front end, which is really all on one server.

# Nuxt. Js origin

On October 25, 2016, the team behind Zeit.co released Next. Js, a React server rendering application framework. A few hours later, in the same vein as Next. Js, a vue.js-based server-side rendering application framework was created, called Nuxt.js.

Nuxt is a framework for minimalist applications rendered by servers. By abstracting the client and server infrastructures, NuxT.js allows developers to focus more on UI rendering of pages. The purpose is to further encapsulate in Node.js, and then save us the step of setting up the server environment, just follow the rules of the library can easily implement SSR.

Function and characteristics

  • By abstracting the organization of the client/server infrastructure, Nuxt.js focuses on the UI rendering of the application.
  • Nuxt.js presets various configurations needed to develop server-side rendered applications using vue.js.
  • Supports static vue. js applications through the nuxt generate command.
  • Based on the Vue. Js
  • Automatic code layering
  • Server side rendering
  • Powerful routing function, support asynchronous data
  • Static file service
  • ES2015+ syntax support
  • Package and compress JS and CSS
  • HTML header tag management
  • Local development supports hot loading
  • Integrated ESLint
  • Support for various styles of preprocessors: SASS, LESS, Stylus, and more
  • Support for HTTP/2 push

Core principles

Nuxt.js integrates the following components/frameworks for developing complete and powerful Web applications:

  • Vue 2
  • Vue-Router
  • Vuex (introduced only when the Vuex state tree configuration item is configured)
  • Vue server-side rendering (excluding mode: ‘spa’)
  • Vue-Meta

When compressed and gzip, the total code size is 57KB (60KB if Vuex is used).

In addition, Nuxt.js uses Webpack along with vue-Loader and Babel-Loader to handle automated build work of code (such as packaging, code layering, compression, and so on).

The work flow:

Installation (omitted)

See zh.nuxtjs.org/guide/insta…

The directory structure

├─ assets // Organize uncompiled static resources like LESS, SASS or JavaScript │ ├─ readme. md ├─ components Nuxt.js does not extend and enhance the Vue. Js components in this directory, that is, they do not have the asyncData method features as page components do. The directory cannot be renamed without additional configuration. │ │ ├ ─ ─ the README. Md └ ─ ─ the default. The vue ├ ─ ─ middleware / / directory to hold application middleware │ └ ─ ─ the README. Md ├ ─ ─ nuxt. Config. Js / / nuxt configuration file ├ ─ ─ pages // Put the page, │ ├── ├.md │ ├── vue │ ├── ├.js automatic Route production │ ├─ readme.md │ ├─ ├.js automatic Route production │ ├─ readme.md │ ├─ ├.js automatic route production │ ├─ readme.md │ ├─ ├.js ├─ server │ ├─ ├─ ├.htm // ├─ ├─ ├.htm // │ ├─ ├─ ├─ ├─ ├─ ├─ weblog.js │ ├─ ├─ favicon. Ico │ ├─ ├─ ├─ weblog.js │ ├─ ├─ weblog.js │ ├─ ├─ faviconCopy the code

Commonly used API

The life cycle

Nuxt extends the Vue lifecycle

exportDefault {middleware (CTX) {}, server validate (CTX) {}, server asyncData (CTX) {}, server fetch (CTX) {}, // Store data loadbeforeCreate() {// both server and client execute},created() {// both server and client execute},beforeMount () {}, 
  mounted() {} // client}Copy the code

The context object

The available properties of context:

Property field type available describe
app Vue root instance Client & server Contains Vue root instances for all plug-ins. For example, when using Axios, you want to getAxios to obtain
isClient Boolean Client & server Whether from client render (deprecated. Please use process.client)
isServer Boolean Client & server Whether to render from the server (deprecated. Please use process.server)
isStatic Boolean Client & server Whether to generate static (pre-rendered) from Nuxt (deprecated). Use process.static)
isDev Boolean Client & server Whether dev mode is used in production data caching
isHMR Boolean Client & server Webpack Hot Module replacement (Dev mode is used only on the client)
route Vue Router routing Client & server Vue Router Indicates a routing instance
store Vuex data Client & server Vuex. Store instance.onlyVuex data flowThis parameter is available only when the related configuration exists
env Object Client & server For the environment variables configured in nuxt.config.js, seeEnvironment variable API
params Object Client & server The route. The params alias
query Object Client & server The alias of the route. The query
req http.Request The service side Request object of the Node.js API. If Nuxt is used as middleware, this object will depend on the framework you are using.Nuxt generate is not available
res http.Response The service side Response object of the Node.js API. If Nuxt is used as middleware, this object will depend on the framework you are using.Nuxt generate is not available
redirect Function Client & server Use this method to redirect user requests to another route. Redirect ([status,] path [, query]) redirect([status,] path [, query])
error Function Client & server Display the error page with this method: Error (Params). The params parameter should contain the statusCode and message fields
nuxtState Object The client Nuxt state, used by the client to obtain Nuxt state before using beforeNuxtRender, is only available in universal mode
beforeNuxtRender(fn) Function The service side Update using this methodNUXTVariables rendered on the client side, called by fn (which can be asynchronous) {Components, nuxtState}, referThe sample

AsyncData function

  • ** type: **Function

The asyncData method is called before each load of the component (page component only). It can be invoked before a server or route is updated. When this method is called, the first parameter is set to the context object of the current page, and you can use the asyncData method to fetch data and return it to the current component.

export default {
  data () {
    return { project: 'default' }
  },
  asyncData (context) {
    return { project: 'nuxt'}}}Copy the code

Note: Since the asyncData method is called before the component is initialized, there is no way to refer to the component instance object through this within the method.

The fetch function

The FETCH method is used to populate the application’s store data before rendering the page, similar to the asyncData method except that it does not set the component’s data.

  • ** type: **Function

If a page component sets the fetch method, it will be called before each load of the component (on the server or before switching to the destination route).

The first parameter of the FETCH method is the context object of the page component. We can use the FETCH method to fetch data to populate the application’s VUEX state tree. To make the fetch process asynchronous, you need to return a Promise, and nuxt.js waits for that Promise to complete before rendering the component.

Warning: You cannot use this internally to fetch a component instance; fetch is called before the component is initialized

For example, pages/index. Vue:

<template>
  <h1>Stars: {{ $store.state.stars }}</h1>
</template>
<script>
export default {
  fetch ({ store, params }) {
    return axios.get('http://my-api/stars')
    .then((res) => {
      store.commit('setStars', res.data)})}} </script> You can also use async or await mode to simplify the code as follows: <template> <h1>Stars: {{$store.state.stars }}</h1>
</template>
<script>
export default {
  async fetch ({ store, params }) {
    let { data } = await axios.get('http://my-api/stars')
    store.commit('setStars', data)
  }
}
</script>
Copy the code

If you want to call and manipulate store in fetch, use store.dispatch, but be sure to wait internally for the operation to end with async/await:

<script>
export default {
  async fetch ({ store, params }) {
    await store.dispatch('GET_STARS');
  }
}
</script>
store/index.js
// ...
export const actions = {
  async GET_STARS ({ commit }) {
    const { data } = await axios.get('http://my-api/stars')
    commit('SET_STARS', data)
  }
}
Copy the code

By default, the fetch method is not called when the query string changes. If you want to change this behavior, for example, when writing a paging component, you can set it to listen for parameter changes through the watchQuery property of the page component. Learn more about the API watchQuery Page.

Two plug-ins to increase the user experience

@ nuxtjs/toast modules

Toast is one of the most common features of UI frameworks. But if your site doesn’t use a UI framework and alert is ugly, introduce this module:

npm install @nuxtjs/toast
Copy the code

It is then introduced in nuxt.config.js

module.exports = {
    modules: [
    '@nuxtjs/toast'['@nuxtjs/dotenv', { filename: '.env.prod'}] // specify dotenv], toast: {// Toast module configuration position:'top-center', 
    duration: 2000
  }
}
Copy the code

Nuxt then registers the $toast method globally for you to use, which is very convenient:

this.$toast.error('The server is off ~~')
this.$toast.error('Request successful ~~')
Copy the code

Loading method

Nuxt provides a built-in loading progress bar to facilitate page hopping.

/ / to open this.$nuxt.$loading.start() // Finish this.$nuxt.$loading.finish()
Copy the code

See zh.nuxtjs.org/api for more apis

Source analyses

Source code address: github.com/nuxt/nuxt.j…

Source directory:

1. Execute our workflow through the.nuxt file

This is the temporary file generated by our project, and the configuration files for our project are all here. You can see the routing file here. Yes, this is the route file automatically configured by the system, generated according to our Pages folder path. Client. Js and server.js are the same as the server.js entry file configured in SSR and middleware. This is the contents of this temporary file. Nuxt folder, but how this folder is generated, please look down.

2. How was NUXT created

This article mainly studies the operation principle of NUxT, and analyzes a series of things that happen behind it from receiving a NUxT instruction to completing the instruction. Before starting this article, readers must personally experience the use of Nuxt.js, and have certain vue.js related development experience.

By looking at the package.json file in the nuxt.js project directory, we can see the following instructions:

"scripts": { "dev": "nuxt"// Start a server that listens on port 3000 and provides hot-reloading"build": "nuxt build"// Build the entire application, compress and merge JS and CSS files (for production)"start": "nuxt start"// Start a production server (you must run nuxt build first)"generate": "nuxt generate"// Build the entire application and generate a static page for each route (for static servers)}Copy the code

We have never looked at our dependency package, so we will look at it today. Open our nuxt project folder under node_modules and go to the bin directory. We can see several files:

To take a look at how Dev works, let’s start with a snippet that basically performs the following steps:

  async run (cmd) {
    const { argv } = cmd
    await this.startDev(cmd, argv, argv.open)
  },

  async startDev (cmd, argv) {
    let nuxt
    try {
      nuxt = await this._listenDev(cmd, argv)
    } catch (error) {
      consola.fatal(error)
      return
    }
    try {
      await this._buildDev(cmd, argv, nuxt)
    } catch (error) {
      await nuxt.callHook('cli:buildError', error)
      consola.error(error)
    }
    return nuxt
  },
Copy the code

So what is the Nuxt () class and what methods does it implement?

Each step in the figure above can be navigated by itself in concrete code. After the user enters the instruction and instantiates the Nuxt() class

The Nuxt() class also provides a close() public method to shut down the server it started.

3, build() to compile

In simple terms, the build() method, after determining the run conditions, initializes the output directory. Nuxt, and then generates a set of configurations from the file structures in the different directories, which are written to template files and output to the.nuxt directory. Next, different WebPack configurations are invoked to run different WebPack build scenarios depending on the development environment.

4, render. Js file package output render

Find render. Js in the nuxt/lib directory, which contains the three methods we are going to analyze :render(), renderRoute(), and renderAndGetWindow().

From this image, we can see that nuxT’s logic for handling “client side rendering” and “server side rendering” is quite clear.

  • First, after the Render () method has handled a series of path problems, it calls the renderRoute() method to retrieve the response and complete the response.
  • The renderRoute() method determines whether the current response should be rendered on the server side. If so, call the bundleRenderer() method provided by Vue to render the HTML content and output it as a whole. If not, print one directly

    String, rendered by the client.

  • Finally, the output HTML is checked for problems with renderAndGetWindow(), and a notification is issued indicating that the HTML is available.

Packaged deployment

Upload the entire code to the server itself to perform compilation packaging:

npm run build
npm run start
Copy the code

Docker+K8S is recommended

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — – personal project — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —

Project introduction

  • Project address: www.ffbig.cn/ The project is based on the summary and sorting of the blogger’s own career skills, and the content is constantly being enriched. The full-stack big front-end series is divided into three phases:
  • 1. Comb the basic knowledge and common technology stack
  • Phase 2: Learning cross-end fusion technology and understanding the “big front End”
  • Proficient in “full stack” with server technology

Project outline

If you find any errors in this project, please submit issues for correction.

Study and communication

Built a “full stack big front end” wechat exchange group, welcome pure technical exchange enthusiasts to join!