Vue SSR server rendering (small white solution)

> Beginology SSR enters the pit

Amazing VUE server rendering is very confused, we most of our front ends are half-way home, and they are separated by the front and rear ends. I don’t know on the server. Do not say java, PHP language, even Node services have not been understood, understanding the server rendering is still difficult;

There are very many Vue service rendering in the Internet, but I have seen it for a long time. A lot, or a mist, do not understand the contact and meaning of these documents and keywords:

  • Entrt-client.js
  • Server -JS
  • Vue-ssr-server-bundle.json
  • Vue-srclientmanifest.json
  • CreateBundlerenderer
  • ClientManifest
This content will be rendered according to the basics – Vue instance rendering – Join Vuerouter – Add Vuex’s order into the pit, follow-up should also have – development mode – -SEO optimization – some rendering, here is not excavated so many pits;

> Basic server rendering

As the name suggestion, get a service: (built a New project, do not use Vue-CLI)


// Server.jsconst Express = Require (‘Express’); Const chalk = Require (‘chalk’); // Add a chalk is the console look. . Const server = expression (); sERVER.GET (REQ, RES) => {res. set (‘content-type’, “text / html”); res. is (`

vue ssr服务端渲染(小白解惑)

Hello
Hello
  `)}) Server.Listen (8080, function () {let = Getipadress (); console.log (` server ON: http: //$}: "green(ip) 8:00$} os module under os module under {// node can get the part of the server to start the server's part of the server side information VAR Interface = Require ('OS'). NetWorkinterface (); for (Var DevName In Interfaces) {var iface = interfaces [devname]; for (var i = 0; i      Start Node Server.js    Normal, this is the most basic server rendering  < iface.length; i++) {
  var alias = iface[i];
  if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
   return alias.address;
  }
 }
}
}
 

It is actually a GET request, returns a string, the browser defaults to return the result;

vue ssr服务端渲染(小白解惑)

However, the resolution of this string is not clear, what is the meaning, such as:


vue ssr服务端渲染(小白解惑) Remove this sentence, the page will become like this, the reason is not refined, the Baidu



> Join the Vue instance

vue ssr服务端渲染(小白解惑) Skip the official website sayingT-Server-bundle.js application means that this file is not used, just a transition file, and the project will not be used. Use the CreateBundlerenderer method to see the current directory structure directly with Vue-Sr-Server-bundle.json;

:

vue ssr服务端渲染(小白解惑)

Add 5 files; Configuration of client-side entry-client.js is not required, here no matter;

app.js is used to create a Vue instance;

Entry- Server.js is used to create the configuration accessories required to generate Vue-SSR-Server-bundle.json (need to use App.js); it is used for WebPack.server.config.js;


WebPack .server.config.js is used to generate Vue-Sr-Server-bundle.json;

Vue-sr-server-bundle.json is used to createBundlereere in Server.js. vue ssr服务端渲染(小白解惑)

// app.js import vue from ‘vue’Import vue from’ ./app.vue’// Here you must write .Vue, or you will match App.JS, Require is not case sensitive 0.0export default createapp = function () {return new Vue ({render: h => h (app)}}

A createApp generates a Vue instance;

// app.Vue

This is an app
  (123)  
has not been used

// Weback-Base.config.jsconst Path = Require (‘Path’) const vueloaderplugin = Require (‘Vue-loader / lib / plugin’) module.exports = {Output: {path: path. Resolve (__ DIRNAME, ‘. / DIST’), FileName: ‘build.js’,}, module: {rules: [{test: / \. JS $ /, us: {loader: ‘Babel-loader’, Options: {Presets: [‘@ Babel / PRESET-ENV’]}}, Exclude: [/ Node_Modules /, / Assets /]}, {Test: / \. Vue $ /, Use: [‘Vue-Loader’]}] }, resolve: {alias: {‘@’: path.resolve (__ DIRNAME, ‘.. /’)}, extensions: [‘. js’, ‘. vue’, ‘. json’]}, plugins: [New Vueloaderplugin ()]}
   About the WebPack configuration 
// WebPack.server.config.js To generate VUE-SSR-server-bundle.jsonconst merge = require ( 'webpack-merge') const baseConfig = require ( './ webpack.base.js') const VueSSRServerPlugin = require ( 'vue-server-renderer / server-plugin') module. Exports = merge (baseconfig, {entry: './entry-server.js', // This allows WebPack to process dynamic imports in Node-Approrate Fashion, // and also compile VUE When the component, // inform the `Vue-loader` Deliver server-oriented code. Target: 'node', // Provide Source Map for Bundle Rendere Support DevTool: 'Source-Map', // Server Bundle uses the Node-style exports Output: {librarytarget: 'commonjs2'}, // This is a plugin that builds the entire output // of the server as a single JSON file. // Default file named `Vue -ssr-server-bundle.json` plugins: [New vuessrserverplugin ()]})
This configuration can be found, the focus is VuessrServerPlugin plugin, generate VUE- SSR-Server-bundle.json is relying on itIf you remove it, it is built-server-bundle.js; About Merge plugin, librarytarget, Target configuration problem ourselves Baidu WebPack to 0.0;
// entry-server. Jsimport {createapp} from ‘./src/app’Export default context => {return createApp ()}

fixed writing method, returns a function for CreateBundlenderer;

Generates Vue-SSR-Server-bundle.json
   The plug-in installed so far is: 

You can do one by one.
 Generates Vue-Sr-Server-bundle.json, uses the webpack command   
Everything is manually, familiar with Webpack;

 Modified Server.js   
Const Express = Require (‘Express’); Const Chalk = Require (‘Chalk’); Const Server = expression (); const serverbundle = Require (‘./ dist / vue-sr-server-bundle.json’) // ** Add * // const renderer = Require (‘Vue-Server-Renderer’) .createbundlerenDere (ServerBundle, {RuninnewContext: false, // Look at the name is also generated a new Context object, default is true, change to false is understood as a cache mechanism, improve server efficiency Template: Require (‘fs’). ReadFileSync (‘./ Index.html’, ‘UTF-8’),}) // ** Add ** // server.get (‘*’, (Req, Res) => {//Res.set (‘Content-Type’, “Text / HTML”); //Res.end (`//
Hello

//

// Hello / / [/) Change to the following const context = {// The parameters here are now useless, but this object is still used, to do Rendertostring parameters URL: Req.url} renderer.rendertostring (Context, (Err, HTML) => {if (err) {res.status (500) .end (‘Internal Server Error’) Return} else {RES.END (HTML)}}) `)}) Server.Listen (8080, function () {let ip = getipadress (); console.log (` server ON: http: // $ {chalk.green (ip)}: $ {chalk.yellow.yelow (8080)})}) Function getipadress () {// node OS module under the part of the server that starts the server, fineThe day goes to node to check VAR interfaces = Require (‘OS’). Networkinterfaces (); for (var defname in interfaces) {var iFace = interfaces [devname]; for (var i = 0; i


Try: Node Server.js

vue ssr服务端渲染(小白解惑)

Normal, the official website of the arrow finger is explained. Don’t forget INDE. Add a line of comments in HTML:


vue ssr服务端渲染(小白解惑) Title, the META header is a similar comment, the principle is that the regular match replacement string –.-;

> Add to route Vue-router

vue ssr服务端渲染(小白解惑)

 need to be modified The documents are:   APP.VUE / / Plus Router-View Put       
//app.jsimport vue from 'Vue'Import App from' ./app.Vue'Import Router from './Router'Export Function CreateApp () {const App = New Vue ({Router, Render: h => h App)}) Return {App, Router}} < iface.length; i++) { var alias = iface[i]; if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) { return alias.address; } } } }
Both the app instance and the router, give Entry-Server.js


// entry-server.jsimport {createapp} from ‘./src/app’Export default context => {// There are many reasons for using Promise, one is The onReady method below is asynchronous. createBundleRenderer support promise return new Promise ((resolve, reject) => {const {app, router} = createApp () router.push (context.url) router.onReady (() => {// onReady method also getMatchedComponents Method Still need to understand const matchcomponents = router.getmatchs () if (! Matchedcomponents.length) {Return Reject ({Code: 404})} resolve (app)}, reject)}}

vue ssr服务端渲染(小白解惑)

Looking at Router.js

vue ssr服务端渲染(小白解惑)

// Router.js import vue from ‘Vue’ import Vuerouter from ‘Vue-router’ // page First declare, don’t ask why IMPORT Home from ‘./pages/home’import store from’ ./pages/store’vue.use (Vuerouter )Export Default New Vuerouter ({MoDe: ‘History’, Routes: [{PATH: ‘/’, Name: ‘Home’, Component: Home}, {Path: ‘/ Store’, Name: ‘Store’, Component: Store},]})

Take a look at the code of the two pages;


//store.Vue

THIS Is Store vue ssr服务端渲染(小白解惑)

The change is almost, try it: Re-play Bag Webpack –config WebPack.server.js

Start Node Server vue ssr服务端渲染(小白解惑)

 > entry-client.js is dry  
It has not been used until the entry-client.js called the client configuration, not urgent use, first do a test, write some logic Try:
Modified Store.Vue

// store.Vue
{msg}
   Export Default {data () {msg: 'this is Store '}, created () {this.msg =' this is created '}, mounted () {this.msg =' this is mounted '}, methods: {Run () {Alert (' this is mEthods')}}}} 
Look at the result of this appearance page should be this is mounted, however, the result is like this:

  It is well explained that the server is also very correct for the understanding of the hook function, and create is executed before the page returns, and the mounted is executed after the Vue instance is formed, that is After the page rendering, this is to execute on the client, but why didn't the page do not perform MOUNTED, and Run's click event does not take effect;  
Take a look:

A JS file is not loaded, how to perform logic, is a static page 0.0;
   At this time, entry-client.js appease 
Added two files
// entry-client.js import {createapp} from ‘./src/app.js’; const {app} = createapp (); app. $ mount (‘ # app ‘);

Basic Configuration;

// WebPack.Client.config.jsconst Merge = Require (‘WebPack-Merge’) const baseconfig = Require (‘./ WebPack.Base.config. JS ‘) Const VuessrClientPlugin = Require (‘ Vue-ServEr-renderer / client-plugin ‘) module.exports = merge (baseconfig, {entry:’ ./entry-client.js’, Optimization: {runtimechunk: true}, plugins: [// This plugin is in the output directory / / Generate `Vue-Sr-Client-Manifest.json`. New VuessrClientPlugin (),]}) vue ssr服务端渲染(小白解惑)

This place focuses on the Vue-SSR-Client-Manifest in this place Optimization, Optimization is a WebPack4 product, which is used to separate the generation of CHUNK. The configuration is complicated. You can see the WebPack4 Optimization summary

Modified SERVER.JS


// Server.js const express = Require (‘express’); const chalk = Require (‘ chalk ‘); const server = expression (); const serverbundle = required (‘ ./ DIST / Vue-ssr-server-bundle.json ‘) const clientmanifest = Require (‘ ./ dist / vue-sr-client-manifest.json ‘) // Add const renderer = Require (‘ Vue-Server-Renderer ‘). CreateBundlerenderer (ServerBundle, {RuninnewcOnText: false, // Recommended Template: Require (‘fs’). ReadFileSync (‘./ Index.html’, ‘UTF-8’), ClientManifest // // New}}} (‘*’, (REQ, RES) => {res., “text / html”); const context = {url: Req.url} renderer.rendertostring (Context, (ERR, HTML) => {IF (Err) {RES.STATUS (500) .end (‘Internal Server Error’) Return} Else {RES.END (HTML)}}}) Server.Listen (8080, Function () {let ip = getipadress () Console.log (`server Opening: http: // $ {chalk.green (ip)}: $ {chalk.yellow.yellow.Yellow.Yellow (8080)}}) Function GetIPadress () {// node OS module can be Get some information for the server that starts the file, details you go to Node to check VAR Interfaces = Require (‘OS’). Networkinterface (); for (Var DevName In Interfaces) {var iFace = interfaces [devname]; for i = 0; i
   Under the package: 
WebPacK --Config Webpack.Client.config.js
Node Server, look at the page


js is there, but why can’t it still do, can’t point 0.0;

vue ssr服务端渲染(小白解惑) Take a look. Olympic error


Read less static file;


Modify server.js plus a static file hosting:

vue ssr服务端渲染(小白解惑)
Take a look



event is also, the page has no change, Console, found that the value has changed, just lost the response; this is why it is necessary to use Vuex;

vue ssr服务端渲染(小白解惑)
> Join Vuex

Start wanting on the page In the THIS. $ Set method, however, it is not possible, and it is impossible to rewrite this method for each value;
   Add a Sotre .js 
// Store.jsimport Vue from ‘Vue’Import Vuex from’ Vuex’Vue.use (Vuex) Export Default New Vuex.Store ({State: { Msg: ”}, Actions: {setmsg ({commitmsg ({commit}, val) {commission (‘setmsg’, val)}}, mutations: {setmsg (state, val) {Vue.Set (State, ‘MSG’, VAL) // Key}}})

Very basic logic, the key in the Vue.set method, re-increase Responsive; modified App. JS
   
// app.js import vue from ‘Vue’Import App from’ ./app.vue’Import Router from APP.Vue’Import Router from ‘./router’Import store from’ ./store ‘{加 加 就 {({router, store, render: h => h (app)}) Return} {Router, Store, Render: h => h (app)}) return { App, Router}}

Store.Vue is modified to be such


  {{msg }} < iface.length; i++) {
    var alias = iface[i];
    if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
     return alias.address;
    }
   }
  }
 } 
EXPORT DEFAULT {Data () {}, create () {this. $ Store.dispatch (‘setmsg’, ‘this is created’)}, compute: {msg () { Return this. $ store.State.msg;}}, mounted () {this. $ store.dispatch (‘setmsg’, ‘this is mounted “}}}}}}}}}: {run () {Alert (‘ this is methods” }}}

Re-taking a package, think about it, if you need to re-package the client, if you modify the app.js, you must re-package it;
Node Server

This time is finalized; vue ssr服务端渲染(小白解惑)

> Summary

The server rendering is quite a lot, involving the field is also very wide, such as Vue, Webpack, Node, their ecosystems are terrible, there is a lot of learning, vue ssr服务端渲染(小白解惑) pit, and big, Also deep, there are still many problems to be solved:


How to do SEO optimization after the asynchronous data is loaded; // HTML Back to render some of the data obtained by the interface to how to do SEO optimization; // For important reasons for server rendering, processing asynchronous data load issues is also how to add this cache; development environment is built; // You don’t want to change your package once, restart it, 0.0 how to implement it. Some page SSR; // A project is not possible to render all pages, too performance, large performance;


There are still a lot of doubts: vue ssr服务端渲染(小白解惑)
Why do you lose your response, how to configure it in WebPack. .

The above is all the content of this article, I hope to help everyone, I hope everyone will support Tumi Cloud.

© Copyright Notice
THE END
Just support it if you like
like0
share
comment Grab the couch

Please log in to comment