The first day of entry: The front-end leader taught me how to get started with Vue server-side rendering (SSR)

I successfully got the OFFER after Xi'an Dianmian some time ago. Today (May 2nd) is my first day of employment. After a short internal training for a morning, the front-end leader let me first understand what is server-side rendering in vue (SSR) .

SSR, the full English name is Server side rendering, the Chinese call it server side rendering.

The first time I heard this term, my head was a little dizzy. Let's first go to the official website to understand the definition of SSR:

Vue.js can render the same components as HTML strings on the server side, send them directly to the browser, and finally "mix" the static markup into a fully interactive application on the client side. This kind of code program that can be run on both the server and the client can also be called "isomorphism".

I weakly asked the leader, why does our company use server-side rendering ?

There are two reasons for the leader's cold reply. First, because our company's site pays great attention to SEO, and the page acquires content asynchronously; second, we also hope that users can see the fully rendered page faster, so that Improve user experience. Based on these two points, server-side rendering (SSR) is needed to solve these problems.

So what is the process of server-side rendering? Without further ado, let’s start with the picture:

 

When using server-side rendering, you must first have a server-side. Because when developing a vue project, you need to start a webpack-dev-server service, port 8000. Because we want to use its hot replacement, it can speed up development efficiency.

 

Since webpack is an autonomous server, we have no way to add server-side rendering code in it, and this code needs to be written by ourselves, so we need to start a node server to execute the logic of server-side rendering. We will use the vue-server-renderer package to help us render the HTML code generated by the vue code in the node.js environment. This part of the code is directly returned to the user, and the user can see the HTML directly in the browser. Content.

 

Taking the picture as an example, we see two rendering processes and two servers. If you directly access webpack-dev-server, it is a pure front-end rendering process just like the process we developed before. If we want to take the server-side rendering process, we need to take the node server service, and the port is 3333 to show the difference. And you need to package a logic to run on the node side, and use webpack-server-compiler to generate a server bundle, which is app.js on the server side. When the node server obtains the server bundle, it can execute vue-server-renderer to render the HTML code and return it directly to the user. In this way, there is no need to render the page content through js, which reduces the user's waiting time. .

 

The main task of this article today is to first create a configuration file with webpack to package the server-side code.

The first step of getting started, how to write a configuration file for server-side rendering?

 

First of all, we need to find the build folder in the project root directory, and then create a new webpack.config.server.js file under it. The specific configuration code, I will use it first:

const path = require('path')
const ExtractPlugin = require('extract-text-webpack-plugin')
const webpack = require('webpack')
const merge = require('webpack-merge')
const baseConfig = require('./webpack.config.base')
const VueServerPlugin = require('vue-server-renderer/server-plugin')

let config

config = merge(baseConfig, {
  target: 'node',
  entry: path.join(__dirname, '../client/server-entry.js'),
  devtool: 'source-map',
  output: {
    libraryTarget: 'commonjs2',
    filename: 'server-entry.js',
    path: path.join(__dirname, '../server-build')
  },
  externals: Object.keys(require('../package.json').dependencies),
  module: {
    rules: [
      {
        test: /\.styl/,
        use: ExtractPlugin.extract({
          fallback: 'vue-style-loader',
          use: [
            'css-loader',
            {
              loader: 'postcss-loader',
              options: {
                sourceMap: true
              }
            },
            'stylus-loader'
          ]
        })
      }
    ]
  },
  plugins: [
    new ExtractPlugin('styles.[contentHash:8].css'),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development'),
      'process.env.VUE_ENV': '"server"'
    }),
    new VueServerPlugin()
  ]
})

module.exports = config

 

New to SSR's children's shoes, do you feel a little dizzy after reading the above code? Don't worry, I'll take you to analyze it one by one.

 

target: 'node',

The target needs to be specified as node, because the packaged program runs on the node side, not the browser side, so the target to be packaged is the node environment.

 

entry: path.join(__dirname, '../client/server-entry.js'),

entry needs to provide a separate entry file, so you need to create a new server-entry.js file in the client folder.

 

devtool: 'source-map',

Devtool needs to specify source-map, because vue-server-renderer has a webpack plug-in, which can provide code debugging functions, but it can only prompt which line of the error file is.

 

libraryTarget: 'commonjs2',

Specify the type of libraryTarget as commonjs2, which is used to specify the form of the entry where the code is exported. In node.js, the module is module.exports = {...}, and the code export form packaged by commonjs2 is similar to this.

 

externals: Object.keys(require('../package.json').dependencies),

externals means external factors, first we can open the package.json file to see dependencies

 

What we get with Object.keys() is an array. Externals is to tell webpack not to package the js code in node_modules. There are some tool-type things in devDependencies, which are not needed when the application is actually running. It is only needed when performing some packaging, tooling operations.

 

'process.env.VUE_ENV': '"server"'

This is what the vue server officially recommends us to do. This attribute may be used in vue-server-renderer.

 

const VueServerPlugin = require('vue-server-renderer/server-plugin')

This plugin can help us generate a json file separately, which can help us deal with some very complex logic in the server-side rendering of Vue.

 

finally

The article is written here, the introductory work of Vue's server-side rendering is completed (first use webpack to create a configuration file to package the server-side code), the next article will introduce how to use koa, the node server-side framework, to implement node server, The latest articles will be updated in my public account < Uncle Runtu > as soon as possible. Welcome to pay attention.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325359844&siteId=291194637