vue2/packages/vue-server-renderer/index.js

40 lines
1.0 KiB
JavaScript
Raw Normal View History

'use strict'
2016-04-27 01:29:27 +08:00
const createRenderer = require('./create-renderer')
const Module = require('./module')
const stream = require('stream')
function runAsNewModule (code, context) {
const path = '__app__'
const m = new Module(path, null, context)
2016-06-25 12:05:39 +08:00
m.load(path)
m._compile(code, path)
const res = Object.prototype.hasOwnProperty.call(m.exports, 'default')
2016-06-25 12:05:39 +08:00
? m.exports.default
: m.exports
if (typeof res.then !== 'function') {
throw new Error('SSR bundle should export a Promise.')
}
return res
2016-06-08 09:53:43 +08:00
}
2016-06-25 12:05:39 +08:00
exports.createRenderer = createRenderer
2016-06-08 09:53:43 +08:00
exports.createBundleRenderer = function (code, rendererOptions) {
const renderer = createRenderer(rendererOptions)
2016-06-08 09:53:43 +08:00
return {
renderToString: (context, cb) => {
runAsNewModule(code, context).then(app => {
renderer.renderToString(app, cb)
})
2016-06-08 09:53:43 +08:00
},
renderToStream: (context) => {
const res = new stream.PassThrough()
runAsNewModule(code, context).then(app => {
renderer.renderToStream(app).pipe(res)
})
return res
2016-04-27 01:29:27 +08:00
}
}
}