0

我从静态站点尝试 ssr

我正在使用 vue、webpack、express 开发代码

如果当前问题是在开发模式下,如果改代码刷新一下,接收到的是第一次构建的html文件。

包版本

"webpack": "^3.6.0",
"webpack-dev-middleware": "^2.0.6",
"webpack-hot-middleware": "^2.25.0"

这是我的完整代码


const express = require('express')
const server = express()
const fs = require('fs')
const path = require('path')
const { createRenderer } = require('vue-server-renderer')

const isDevelopment = process.env.NODE_ENV === 'development'

let renderer
if (isDevelopment) {
  const webpack = require('webpack')
  const webpackConfig = require('./build/webpack.dev.client.js')

  const webpackDevMiddleware = require('webpack-dev-middleware')
  const webpackHotMiddleware = require('webpack-hot-middleware')

  const compiler = webpack(webpackConfig)
  const middleware = webpackDevMiddleware(compiler, {
    index: false,
    noInfo: true,
    publicPath: webpackConfig.output.publicPath,
  })

  server.use(middleware)
  server.use(
    webpackHotMiddleware(compiler, {
      log: false,
      path: '/__webpack_hmr',
      heartbeat: 2000
    })
  )

  compiler.plugin('done', (stats) => {
    const template = middleware.fileSystem.readFileSync(webpackConfig.output.path + '/index.html', 'utf-8')
    renderer = createRenderer({
      runInNewContext: false, // false or once
      template
    })
  })
} else {
  renderer = createRenderer({
    runInNewContext : 'false`', // false or once
    template : fs.readFileSync(path.resolve(__dirname, '../index.html'), 'utf-8'),
  })
}

server.use('/static', express.static(path.join(__dirname, '../static')));
server.use('/static', express.static(path.join(__dirname, '../static')));

// this bundle file contains a server pre fetch code.
const bundle = require('./server.bundle.js')
server.get('*', (req, res) => {
  const { url, query, path, cookies, params } = req;
 
    bundle.default({ url, query, path, cookies, params }).then((app) => {
      renderer.renderToString(app, {}, function (err, html, data) {
        if (err) {
          if (err.code === 404) {
            res.status(404).end('Page not found')
          } else {
            console.log(err)
            res.status(500).end('Internal Server Error')
          }
        } else {
          const dataStr = app.preFetchData 
            ? `<script type="application/json" id="prefetch-data">${JSON.stringify(app.preFetchData)}</script>`
            : '';
            
          html = html.replace('##title##', app.head.title);
          html = html.replace('##meta##', app.head.meta);
          html = html.replace('##data##', dataStr);
          res.send(html)
        }
      })
    }, (err) => {
    })

})

module.exports = server

compiler.plugin('done', (stats) => {
    const template = middleware.fileSystem.readFileSync(webpackConfig.output.path + '/index.html', 'utf-8')
    renderer = createRenderer({
      runInNewContext: false, // false or once
      template
    })
  })

当我更改此代码中的代码时,我想收到更新的 html 文件

4

0 回答 0