Ai
1 Star 0 Fork 0

Vue.js/vue-ssr-html-stream

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
index.js 2.53 KB
一键复制 编辑 原始数据 按行查看 历史
尤雨溪 提交于 2017-03-27 15:50 +08:00 . support asyncChunks
const Transform = require('stream').Transform
const serialize = require('serialize-javascript')
class HTMLStream extends Transform {
constructor (options) {
super()
this.started = false
const template = parseTemplate(options.template, options.outletPlaceholder)
this.head = template.head
this.neck = template.neck
this.waist = template.waist
this.tail = template.tail
this.context = options.context || {}
}
_transform (data, encoding, done) {
if (!this.started) {
this.emit('beforeStart')
this.started = true
this.push(this.head)
// inline server-rendered head meta information
if (this.context.head) {
this.push(this.context.head)
}
// inline server-rendered CSS collected by vue-style-loader
if (this.context.styles) {
this.push(this.context.styles)
}
this.push(this.neck)
}
this.push(data)
done()
}
_flush (done) {
this.emit('beforeEnd')
// inline initial store state
if (this.context.state) {
this.push(renderState(this.context.state))
}
this.push(this.waist)
if (this.context.asyncChunks) {
this.push(this.context.asyncChunks)
}
this.push(this.tail)
done()
}
}
function parseTemplate (template, contentPlaceholder = '<!--vue-ssr-outlet-->') {
if (typeof template === 'object') {
return template
}
let i = template.indexOf('</head>')
const j = template.indexOf(contentPlaceholder)
if (j < 0) {
throw new Error(`Content placeholder not found in template.`)
}
if (i < 0) {
i = template.indexOf('<body>')
if (i < 0) {
i = j
}
}
let waist = ''
let tail = template.slice(j + contentPlaceholder.length)
let k = tail.indexOf('</script>')
if (k > 0) {
k += '</script>'.length
waist = tail.slice(0, k)
tail = tail.slice(k)
}
return {
head: template.slice(0, i),
neck: template.slice(i, j),
waist,
tail
}
}
function renderTemplate (parsedTemplate, content, context = {}) {
return (
parsedTemplate.head +
(context.head || '') +
(context.styles || '') +
parsedTemplate.neck +
content +
(context.state ? renderState(context.state) : '') +
parsedTemplate.waist +
(context.asyncChunks ? context.asyncChunks : '') +
parsedTemplate.tail
)
}
function renderState (state) {
return `<script>window.__INITIAL_STATE__=${
serialize(state, { isJSON: true })
}</script>`
}
HTMLStream.parseTemplate = parseTemplate
HTMLStream.renderTemplate = renderTemplate
module.exports = HTMLStream
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/vuejs/vue-ssr-html-stream.git
git@gitee.com:vuejs/vue-ssr-html-stream.git
vuejs
vue-ssr-html-stream
vue-ssr-html-stream
master

搜索帮助