Skip to content

How to add ssr to a vue-cli 3 project? #1398

@leonardovilarinho

Description

@leonardovilarinho

In all SSR tutorials with Vue that I found the webpack merge is used to create a configuration for the server. Could you explain quickly how I would do this in the design created by vue-cli 3? I am also using the PWA plugin.

My current code is:

factory.js

...
export default () => new Vue({
  router,
  store,
  render: h => h(App)
})

server.js

const express = require('express')
const { resolve } = require('path')
const fs = require('fs')

global.Vue = require('vue')
const layout = fs.readFileSync(resolve(__dirname, './dist/index.html'), 'utf8')
const renderer = require('vue-server-renderer').createRenderer()

const app = express()
app.use('/dist', express.static(
  resolve(__dirname, './dist')
))

app.get('/ssr', (req, res) => {
  renderer.renderToString(
    require(resolve(__dirname, './src/factory'))(),
    (err, html) => {
      if (err) {
        console.error(err)
        return res.status(500).send('Server error')
      }
      res.send(layout.replace('<div id="app"></div>', html))
    }
  )
})

app.get('*', (req, res) => {
  res.send(layout)
})

app.listen(process.env.PORT || 3000, () => console.log('Running :3000'))

I do not understand how to do it, as it should not be taking the factory.js from the raw code, but compiled.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions