Vue SSR is introduced

SSR Github Demo

What is server-side rendering?

Vue.js is a framework for building client applications. By default, the Vue component can be exported to the browser for DOM generation and DOM manipulation. However, it is also possible to render the same component as HTML strings on the server side, send them directly to the browser, and finally “activate” these static tags into a fully interactive application on the client side.

Why server side Rendering (SSR)?

The main advantages of server-side rendering (SSR) over traditional SPA (single-page Application) are:

Better SEO, thanks to search engine crawler crawler tools can view fully rendered pages directly. Faster time-to-content, especially for slow network conditions or slow-running devices. You don’t have to wait for all the JavaScript to download and execute before the server-rendered markup is displayed, so your users will see the fully rendered page more quickly.

SSR rendering process

As you can see, the Source section on the left is the Source code we wrote. All the code has a common entry, app.js, followed by the server-side entry (entry-server.js) and client-side entry (entry-client.js). After compiling all the source code, we packaged two bundles, namely Server bundle and Client Bundle, through the construction of Webpack. When the user visits the page, first through the server entrance, vUE is assembled into HTML string, and mixed into the HTML template accessed by the client, and finally the whole SSR rendering process is completed.

Nuxt framework

Nuxt is a higher-level framework based on the Vue ecosystem that provides an extremely convenient development experience for developing server-side rendered Vue applications. Even cooler, you can use it as a static station generator.

Nuxt official website introduction

The installation

NPM init nuxt-app <project-name>cd <project-name>
npm run dev
Copy the code

configuration

nuxt.config.js

const path = require('path')
exportDefault {// allows you to use aliases in 'Javascript' and 'Css' to access custom directoriesalias: {
    '~ ~': `<rootDir>`,
    '@ @': `<rootDir>`,
    '~': `<srcDir>`,
    The '@': `<srcDir>`,
    'assets': `<srcDir>/assets`, // (unless you have set a custom `dir.assets`)
    'static': `<srcDir>/static`, // (unless you have set a custom `dir.static`)
    'style': path.resolve(__dirname, './assets/style')}, // define the workspace directory for the application, default process.cwd() rootDir:' ', // Define the applicationsourceDirectory, default value same as rootDir srcDir:' 'Server: {port: 3000, // default: 3000 host:'0.0.0.0', // default: localhost,
    timing: false}, // NPM run generate generate static application generate: {// dir:'dist'
  },

  // trueStart server-side rendering,falseOnly start client rendering SSR:true, / / headers set, Global page headers: https://go.nuxtjs.dev/config-head head: {title:'ssr-demo',
    htmlAttrs: {
      lang: 'en'
    },
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: ' ' }
    ],
    link: [
      { rel: 'icon'.type: 'image/x-icon', href: '/favicon.ico'}}], / / Global CSS, Global CSS: https://go.nuxtjs.dev/config-css CSS: [/ /'ant-design-vue/dist/antd.css'// the CSS suffix can be omitted'assets/style/common'], / / plugins directory of js file is added to the application, the plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins plugins:'@/plugins/antd-ui'.'@/plugins/veui'], / / automatic scanning and import components, need not when use the import components, can be used directly, Auto import components: https://go.nuxtjs.dev/config-components components:true, / / Build Configuration: https://go.nuxtjs.dev/config-build Build: {/ / whether the CSS to independent file / / extractCSS:true// Babel: {plugins: ['veui'['import', {
          'libraryName': 'ant-design-vue'.'libraryDirectory': 'es'.'style': true
            // customStyleName: name => {
            //   return `assets/${name}.css`
            // }
          }
        ] // `style: true'will load less file]}, // can omit the extension resolve: {extensions: ['.js'.'.vue'.'.json']}, // Transpile: ['veui'.'vue-awesome'.'ant-design-vue'], // loader config loaders: {vue: {extractCSS:true
      },
      less: {
        javascriptEnabled: true}}, // Manually extend client and server webpack configuration extend(config, context){// Add loader rule config.module.rules.push({test: / \. Vue $/, / / match. SVG include: [path. Resolve (__dirname,'node_modules/veui'], // add SVG to loader. Use: [{loader:'veui-loader', options: {
                modules: [
                  {
                    package: 'veui-theme-blue',
                    fileName: '${module}.less'
                  },
                  {
                    package: 'veui-theme-blue',
                    fileName: '${module}.js',
                    transform: false}]}}]})}}Copy the code

The Demo sample

1. SSR: true, server rendering

When rendering on the server side, you can see that Preview, which the entry returns, generates good pages on the server side, which is better for SEO and faster display of pages.

2. SSR: false, client rendering

When rendering on the client side, you can see that the Preview returned by the entry is a blank page, and the Dom of the page is dynamically generated on the browser side by extracting other JS.

3. BundleRendererAutomatic inlining of critical CSS

For an introduction to critical CSS, see another article: juejin.cn/post/694647… Pages /index.vue Renders the top page

<template>
    <div class="index"> </div> </template> <style>. } </style>Copy the code

Create pages/test.vue page to verify whether SSR will automatically inject critical CSS

<template>
    <div class="test"> Test </div> </template> <style>test {
    color: red;
}
</style>
Copy the code
  • inindex.vueThe introduction oftest.vueAfter the service is started,test.vueStyles are also embedded in the page in style form

  • Not inindex.vueThe introduction oftest.vueAfter the service is started,test.vueStyles are not embedded in the first render page

Only when visitingtestThis parameter is displayed only for routingtest.vueThe relevant styles

Summary: SSR server will automatically inject the first screen rendering key CSS, no need to introduce other plug-ins.

4. extractExtract the CSS

To enable theextractAfter the CSS is extracted, the styles are extracted into a separate CSS file and introduced as an external chain.

The above is Vue SSR NUXT framework related to the arrangement, every day there are endless new knowledge, come on!!