“Learning without thinking is perilous; thinking without learning is perilous.”

Server Side Rendering (SSR)

SSR stands for server-side rendering and aims to solve SEO problems in single page applications.

Server-side Rendering (SSR) and Client-side Rendering (CSR)

Server-side Rendering (SSR)

The browser requests the HTML document, and the server generates the HTML page (or page component) as an HTML string, returns it to the browser, and renders it directly to the page.

Client Side Rendering (CSR)

The browser first requests an HTML document and loads the JS script in the HTML page on the browser. With the ability of JS (vue/ React), the final rendering of the virtual DOM is filled into the page.

What is the essential difference between the two?

SSR

The server generates good HTML page content and returns it directly to the browser for rendering.

server

const express = require('express')

const app = express()

app.get('/ssr', (req, res) => {
  res.send(`
    <html>
      <head>
        <meta charset='utf-8'> <title>SSR Server Rendering </title> </head> <body> < H3 >SSR Server Rendering </ H3 > < P >SSR means Server Side Rendering, which aims to solve the SEO problem of single page application. </p> </body> </html> `) }) app.listen(7200)Copy the code

Client access page localhost:7200/ SSR

   <html>
      <head>
        <meta charset='utf-8'> <title>SSR Server Rendering </title> </head> <body> < H3 >SSR Server Rendering </ H3 > < P >SSR means Server Side Rendering, which aims to solve the SEO problem of single page application. </p> </body> </html>Copy the code

CSR

The page first outputs an empty div#root, then the client loads and compiles the react code (bundle.js chunk.js and other javascript scripts), and finally renders the page components to the page.

npx create-react-app my-app
cd my-app
yarn start
Copy the code

Browser visit http://localhost:3000/

  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  <script src="/static/js/bundle.js"></script><script src="/static/js/0.chunk.js"></script><script src="/static/js/main.chunk.js"></script></body>
Copy the code

The most important difference between client-side and server-side rendering is who does the full stitching of the HTML file, server-side rendering if it’s done on the server and then returned to the client, and client-side rendering if the front end does more work to finish stitching the HTML.

The front and back end split the core idea

The front end is split, the back end is focused on data interface service, the front end is focused on interface call, page rendering, both sword well, complement each other.

What are the pros and cons of server-side rendering?

Advantages:

  • Better SEO first screen loads faster thanks to search engine crawler crawler tools that can view fully rendered pages directly.
  • The first screen loads quickly to see a fully rendered page, thus improving the user experience.
  • The back end generates static files that parse templates, leaving the client to parse standard HTML pages.

Disadvantages:

  • Development conditions are limited in server-side rendering, and lifecycle hooks other than Created and beforeCreate are not available
  • Occupies server resources
  • In addition to being familiar with Webpack and Vue, it is also necessary to master node and Express technologies. Compared to client rendering, the project construction and deployment process is more complex.

What are the pros and cons of client-side rendering?

Advantages:

  • The front end focuses on the front-end UI, the back end focuses on API development, and the front end has more options than having to follow a back-end specific template.
  • Experience better

Disadvantages:

  • The first screen loads slowly
  • In addition to Google and Bing perfectly implement crawler rendering and content fetching for SPA (single-page Application), most search engines including Baidu do not support it. Therefore, the products that contain rich content and need SEO traffic will naturally need SSR implementation.

Whether server side rendering should be used

  • Slow first screen loading You can perform server rendering for the first screen loading. But to be aware of, once done, late maintenance is a very painful thing. Compared with server rendering, it is recommended to optimize the first screen loading process by applying split and code Spliting (I have done the first screen optimization once before, the first screen loading time was 5s+ each time before optimization, and the first screen loading time became 2s+ directly after code Spliting, which is cost-effective).
  • SEO optimization if it is for the main page site to be included by the search engine, you can use server-side rendering. A better idea would be to start a new bootleg project where static resources or server rendered display pages serve as search engine traffic for major websites.

Vue server render

Nuxt.js Next. Js) vue-server-renderer is an NPM package that is officially provided for us to implement server-side rendering

Basic usage

The installation

npm install vue vue-server-renderer --save
Copy the code

Render a Vue instance

1. Create a Vue instance

const Vue = require('vue')

const app = new Vue({
  template: `<div>hello zhufeng</div>`
})
Copy the code

Create a Renderer object

const renderer = require('vue-server-renderer').createRenderer()
Copy the code

3. Render the Vue instance as HTML

renderer.renderToString(app, (err, html) => {
  if (err) throw err
  console.log(html)
  // <div data-server-rendered="true">hello zhufeng</div>}) // In 2.5.0+, if no callback is passed, a Promise is returned:  renderer.renderToString(app).then(html => { console.log(html) }).catch(err => { console.error(err) })Copy the code

Vue instance rendering complete sample code

Node.js server serves as the middle tier

npm i express --save
Copy the code
const Vue = require('vue')
const server = require('express'Const renderer = require()'vue-server-renderer').createrenderer () // Create a back-end route server.get('/', (req, res) => {// Create an instance of Vue const app = new Vue({data: {title:'hello zhufeng'}, template: <h3>{{title}}</h3> '}) // Convert Vue instances to HTML renderer.rendertoString (app). Then (HTML => { console.log(html) //'<h3 data-server-rendered="true">hello zhufeng</h3>'// Finally, the spliced HTML page content is returned to the browser res.send(' <! DOCTYPE html> <html lang="en">
          <head><title>Hello</title></head>
          <body>${html}</body>
        </html>
      `)
    })
    .catch(err => {
      res.status(500).end('Internal Server Error')
    })
})

server.listen(7300)

Copy the code

Use HTML page templates

Create an HTML template page and wrap the container with an additional HTML page to wrap the generated HTML markup.

HTML template

<! DOCTYPE html> <html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title> SSRS </title> </head> <body> <! --vue-ssr-outlet--> </body> </html>Copy the code

Note that <! — VUe-SSR-outlet –> Comments — This is where the application’s HTML tags will be injected.

The server side

const Vue = require('vue')
const fs = require('fs')
const server = require('express')()

const { createRenderer } = require('vue-server-renderer'Const renderer = createRenderer({template: fs.readfilesync ())'./template/index1.html'.'utf-8'}) // Create a back-end route server.get('/', (req, res) => {// Create an instance of Vue const app = new Vue({data: {title:'hello zhufeng'}, template: <h3>{{title}}</h3> '}) // Convert Vue instances to HTML renderer.rendertoString (app). Then (HTML => {// Send (HTML)}). Catch (err => {res.status(500).end('Internal Server Error')
    })
})

server.listen(7300)

Copy the code

Dynamically inject title and meta tags

HTML template sets interpolation variables

<! DOCTYPE html> <html lang="en"> <head> {{{meta}}} <title>{{title}}</title> </head> <body> <! --vue-ssr-outlet--> </body> </html>Copy the code

We can provide interpolation data by passing in a “render context object” as the second argument to renderToString:

// Dynamically inject title and meta tags const context = {title:'Everest Front End Training',
    meta: `
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="keywords" content="HTML, CSS, Vue, React, Node, JavaScript"Renderer. RenderToString (app, Context).then(HTML => {// Finally return the stitched HTML page content to the browser res.send(HTML)}). Catch (err => {res.status(500).end(err => {res.status(500).end('Internal Server Error')})Copy the code

Reference source

Github.com/Lwenli1224/…

Writing generic code

“Generic” code – that is, code that runs on both the server and the client. Because of differences in use cases and platform apis, our code will not be exactly the same when running in different environments. So here are the key things you need to understand.

Problems needing attention in SSR development

  • Server rendering only executes vUE’s two hook functions beforeCreate and Created

  • Server rendering cannot access global objects such as Window and document that are only available to browsers.

For example, AXIos is an HTTP client that exposes the same API to both the server and client.

Webpack engineering construction

Each server and client needs to provide a Vue application. To do this, we need to use WebPack to package our Vue application. In fact, we may need to package Vue applications on the server using Webpack because:

  • Typically Vue applications are built from Webpack and vue-loader, and many Webpack-specific functions cannot run directly in Node.js (e.g. importing files through file-loader, importing CSS through CSS-loader).

  • While the latest versions of Node.js fully support ES2015 features, we still need to translate the client code to accommodate older browsers. This also involves a build step

Then our Server code and Client code are respectively packaged through Webpack to generate the Server Bundle and Client Bundle

  • The server needs a “server bundle” for server-side rendering (SSR)

  • The client bundle “is sent to the browser for blending static tags.

Building Vue development Environment from scratch (SSR)

Vue – Server – Renderer was used to build vUE SSR development environment

Git repository source

From zero everyone vUE SSR environment is more laborious

Github.com/Lwenli1224/…

Build a vUE environment from zero: webPack4 + vue-loader + babel-loader v8 + Babel v7 + esLint + Git hooks + EditorConfig

juejin.cn/post/1

Server rendering application framework -Nuxt.js

Nuxt.js is a server rendering application framework based on vue.js. You can use it to initialize infrastructure code for new projects, or to use nuxt.js in existing Node.js projects. Nuxt.js presets various configurations needed to develop server-side rendered applications using vue.js.

create-nuxt-app

Scaffolding tools created by the Nuxt.js team

Create a NUXT project

npx create-nuxt-app nuxt-app
Copy the code

It lets you make integration choices such as a server-side framework (Express KOA) and a UI framework.

Start the project

npm run dev
Copy the code

Now our application runs at http://localhost:3000.

Note: Nuxt.js listens for file changes in the Pages directory, so there is no need to restart the application when adding a new page.

The directory structure

├ ─ ─ the README, md# Documentation├ ─ ─ assetsThe resource directory is used to organize uncompiled static resources such as LESS, SASS, or JavaScript├ ─ ─ the componentsThe component directory is used to organize vue.js components of an application├ ─ ─ layoutsThe layout directory is used to organize the layout components of an application├ ─ ─ middlewareThe middleware directory is used to store the middleware of the application.├ ─ ─ nuxt. Config. JsThe # nuxt configuration file is used to organize the personalized configuration of the nuxt.js application to override the default configuration.├ ─ ─ pagesThe page directory is used to organize the routes and views of the application├ ─ ─ the pluginsThe plugins directory is used to organize Javascript plugins that need to run before the root vue.js application is instantiated├ ─ ─ serverThe server is used to organize the node middle tier service code├ ─ ─ the staticThe static file directory is used to store the static files of the application├ ─ ─ storeThe # store directory is used to organize the application's Vuex state tree files.
Copy the code

The directory structure details description zh.nuxtjs.org/guide/direc…

Asynchronous data

asyncData

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. You can retrieve data using asyncData methods. Nuxt.js will return the data returned by asyncData to the current component.

fetch

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.

Nuxt.js development practice (build CNode community)

Routing to create

Nuxt.js automatically generates the route configuration of vue-Router module based on the Pages directory structure.

Vuex configuration

Nuxt.js will try to find the store directory under the application root, and if it exists, it will do the following:

  • Reference the VUEX module
  • Add the VUex module to the Vendors build configuration
  • Sets the store configuration item of the Vue root instance

Middleware Configuration

Each middleware should be placed in the Middleware/directory. The filename name will become the middleware name (middleware/auth.js will become auth middleware).

Node Service Configuration

nuxt.config.js

The nuxt.js default configuration covers most usage scenarios and can be overridden with nuxt.config.js.

Zh.nuxtjs.org/api/configu… Github.com/Lwenli1224/…

Nuxt.js CNode community project source code

For more details please see my warehouse source github.com/Lwenli1224/…

To be continued To be updated…

The importance of paper documents

More and more feel that it is very important to study and work at ordinary times to see the documents, especially the first-hand information of official documents. If English is good, it is best to see more first-hand information of English documents.

  • See official documents such as:

    Nuxt.js zh.nuxtjs.org/

    webpack webpack.js.org/

    babel babeljs.io/

  • Learn through NPM search package

    www.npmjs.com/

  • Go to Github to see the source code

    github.com/

  • Check questions on StackOverflow

    stackoverflow.com/

    segmentfault.com/

    www.google.com/?gws_rd=ssl

  • Visit technical community, MDN Nuggets CSDN Expo Park, etc