Home > Web Front-end > uni-app > How to do ssr with Uniapp

How to do ssr with Uniapp

PHPz
Release: 2023-04-14 13:55:36
Original
2375 people have browsed it

UniApp is a cross-platform application development framework based on the Vue.js framework, allowing developers to build iOS, Android, H5 and mini-program applications at the same time. Therefore, in scenarios with high performance requirements, you may need to use SSR (Server-Side Rendering) to solve rendering performance problems. This article will discuss how to implement SSR in UniApp.

What is SSR?
SSR completes the first rendering of the page on the server side, returning the static HTML content to the browser, allowing the browser to see that there is available HTML, and then render the page. The benefit of SSR is that it can make the first load faster and improve the user experience.

UniApp’s SSR implementation method?
UniApp's SSR implementation method is based on the SSR implementation method of Vue.js, which requires the use of some SSR plug-ins in the Vue.js ecosystem.
Two Vue.js plug-ins are introduced below:

  1. Vue-router: used for routing management to associate requests with corresponding components.
  2. Vue-server-renderer: Used to render the HTML string of the application in the Node.js environment, generating HTML files to represent the current state of the application.

The specific implementation method is as follows:

  1. Install Vue-router and Vue-server-renderer:

    npm install vue-router vue-server-renderer --save
    Copy after login
  2. Create the SSR entry file:
    Create the entry-ssr.js file under src with the following content:

    import createApp from './main'
    
    export default context => {
      return new Promise((resolve, reject) => {
     const { app, router, store } = createApp()
     const { url } = context
     const fullPath = router.resolve(url).route.fullPath
    
     if (fullPath !== url) {
       return reject({ url: fullPath })
     }
    
     // 设置 server router 的位置
     router.push(url)
    
     // 等待 router 将组件渲染完
     router.onReady(() => {
       const matchedComponents = router.getMatchedComponents()
       if (!matchedComponents.length) {
         return reject({ code: 404 })
       }
    
       Promise.all(
         matchedComponents.map(Component => {
           if (Component.asyncData) {
             return Component.asyncData({
               store,
               route: router.currentRoute
             })
           }
         })
       )
         .then(() => {
           context.state = store.state
           resolve(app)
         })
         .catch(reject)
     }, reject)
      })
    }
    Copy after login
  3. Create the SSR server:
    Create server.js in the root directory file, the content is as follows:

    const Koa = require('koa')
    const path = require('path')
    const fs = require('fs')
    const koaStatic = require('koa-static')
    const { createBundleRenderer } = require('vue-server-renderer')
    const serverBundle = require('./dist/vue-ssr-server-bundle.json')
    const clientManifest = require('./dist/vue-ssr-client-manifest.json')
    const template = fs.readFileSync(path.join(__dirname, './index.ssr.html'), 'utf-8')
    
    const app = new Koa()
    const renderer = createBundleRenderer(serverBundle, {
      runInNewContext: false,
      template,
      clientManifest
    })
    
    // 静态资源
    app.use(koaStatic(path.join(__dirname, './dist')))
    
    app.use(async (ctx, next) => {
      const context = { url: ctx.url }
    
      const html = await renderer.renderToString(context)
     .catch(err => {
       if (err.code === 404) {
         ctx.status = 404
         ctx.body = '404 Page Not Found'
       } else {
         ctx.status = 500
         ctx.body = '500 Internal Server Error'
         console.error(`${ctx.url}\n${err.stack}`)
       }
     })
    
      ctx.body = html
    })
    
    const port = process.env.PORT || 9090
    
    app.listen(port, () => {
      console.log(`server started at localhost:${port}`)
    })
    Copy after login
  4. Modify the build configuration:
    In the vue.config.js file, add the following code:

    module.exports = {
      productionSourceMap: false,
      css: {
     extract: {
       ignoreOrder: true
     }
      },
      configureWebpack: config => {
     if (process.env.UNI_SSR) {
       config.output.libraryTarget = 'commonjs2'
       config.externals = [
         /^uni-app/,
         /^@dcloudio/,
         {
           vue: {
             root: 'Vue',
             commonjs: 'vue',
             commonjs2: 'vue'
           }
         }
       ]
       config.plugins.push(new VueSSRServerPlugin())
     }
      }
    }
    Copy after login
  5. Modify the package.json file in the root directory:
    Add the following code under "scripts":

    "ssr-build": "cross-env UNI_SSR=1 vue-cli-service build --mode production --target server --dest dist && vue-cli-service build --mode production --target client --dest dist",
    "ssr-start": "cross-env NODE_ENV=production node server.js"
    Copy after login

    Execute npm run ssr-build to build the SSR application, and then execute npm run ssr-start to start the application program.

At this point, UniApp SS has been successfully executed.

Summary
Because the structure of UniApp is very similar to Vue.js, when implementing SSR, UniApp’s SSR can be completed according to the SSR implementation method of Vue.js, and UniApp can be made through a series of steps Applications in support server-side rendering, resulting in faster page loading speeds and improved user experience.

The above is the detailed content of How to do ssr with Uniapp. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template