Vue-cli: How to add ssr to a vue-cli 3 project?

Created on 29 May 2018  ·  6Comments  ·  Source: vuejs/vue-cli

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.

Most helpful comment

Here's an example project that does SSR and uses vue-cli 3—https://github.com/lentoo/vue-cli-ssr-example

All 6 comments

Hello, your issue has been closed because it does not conform to our issue requirements. In order to ensure every issue provides the necessary information for us to investigate, we require the use of the Issue Helper when creating new issues. Thank you!

Here's an example project that does SSR and uses vue-cli 3—https://github.com/lentoo/vue-cli-ssr-example

@eddyerburgh thank you so much! I would never get this result, thanks for your help

Hi , I write a project for cli3-ssr-project example, see here

For vue-cli 4 I've implemented an example following the official vue ssr guide(see the second commit, the first commit is just a default vue cli 4 project created via vue create xxx), the key point is to use the configureWebpack option to integrate your webpack configuration into vue-cli's build process. Hope that helps.

I've created a gist with a diff condensing all of @1isten 's modifications to a default vue cli 4 project

Was this page helpful?
0 / 5 - 0 ratings