prerender-spa-plugin 完整指南:用 Puppeteer 为 webpack SPA 生成预渲染静态 HTML
prerender-spa-plugin 完整指南:用 Puppeteer 为 webpack SPA 生成预渲染静态 HTML
本指南以开源仓库 prerender-spa-plugin(当前稳定版 3.x,基于 Puppeteer)的官方 README 为骨架,系统讲解"预渲染(Prerendering)"这一替代 SSR 的静态站点生成方案:如何把它接入 webpack 构建流水线、完整配置每一个插件选项、选择 Puppeteer / jsdom 渲染器、用 postProcess 精细化改写输出,并解决 Vue.js、内联样式等实战中常见的坑。读完你将能在不改造现有 SPA 代码的前提下,为任意路由批量产出可直接交给静态服务器托管的 HTML 文件。
仓库状态提示:仓库根目录 README 开头标注了
[DEPRECATED],正文明确说明3.x是基于 Puppeteer 的稳定版本;基于 PhantomJS 的2.x已弃用(见 v2 分支)。本文所有内容以当前仓库实际代码与文档为准。
一、什么是预渲染(Prerendering)?
近年来 SSR(服务端渲染)在 JavaScript 前端圈大行其道——在把页面发给客户端之前先在服务端渲染好,听起来很"革命性"。但 README 直言:当年 PHP、ASP、JSP 被吐槽的缺点,如今 SSR 一样具备——慢、容易坏、实现复杂。
而很多场景你其实并不需要 SSR。预渲染的思路是:启动一个无头浏览器(headless browser)加载应用的各个路由,把渲染完成后的结果保存为静态 HTML 文件,然后用你原有的任意静态文件托管方案直接伺服即可。它天然兼容 HTML5 History 导航,无需修改业务代码,也不用引入任何服务端渲染的迂回方案——"它就是用起来有效(It just works)"。
预渲染可能不适合的场景
README 坦诚地列出了两个反例,适合与不适合要分清:
- 路由数量极多:如果你的站点有成百上千条路由,预渲染会非常慢。虽然每次更新只需跑一遍,但可能耗时巨大。大多数项目不会有上千条静态路由,但以防万一,请先评估。
- 动态内容:如果渲染的路由包含"因用户而异"的内容或其他动态数据源,务必准备占位组件,让内容在客户端加载时再填充,否则预渲染出来的页面会"有点怪"。
二、安装与基本用法
插件依赖 @prerenderer/prerenderer、@prerenderer/renderer-puppeteer 与 html-minifier(见 package.json),要求 Node >=4.0.0(engines 字段)。在 webpack 项目中安装:
npm install --save-dev prerender-spa-plugin
Basic Usage(webpack.config.js)
这是 README 给出的最小可用配置,仅需两个必填项:
const path = require('path')
const PrerenderSPAPlugin = require('prerender-spa-plugin')
module.exports = {
plugins: [
...
new PrerenderSPAPlugin({
// Required - The path to the webpack-outputted app to prerender.
staticDir: path.join(__dirname, 'dist'),
// Required - Routes to render.
routes: [ '/', '/about', '/some/deep/nested/route' ],
})
]
}
staticDir:webpack 输出后的应用静态根目录(必填)。routes:需要预渲染的路由列表(必填)。每个路由最终会以路由路径/index.html的形式写出。
仓库中 examples/vanilla-simple/webpack.config.js 就是这一最小用法的完整落地:它把 src/static 复制到 dist,然后对 ['/', '/about', '/some/deep/nested/route'] 三个路由做预渲染,并额外启用了 minify 与自定义渲染事件。
三、Advanced Usage:一份可复制的完整配置
README 用一整段示例展示了插件的全部能力,这里完整保留并逐项注释:
const path = require('path')
const PrerenderSPAPlugin = require('prerender-spa-plugin')
const Renderer = PrerenderSPAPlugin.PuppeteerRenderer
module.exports = {
plugins: [
...
new PrerenderSPAPlugin({
// Required - The path to the webpack-outputted app to prerender.
staticDir: path.join(__dirname, 'dist'),
// Optional - The path your rendered app should be output to.
// (Defaults to staticDir.)
outputDir: path.join(__dirname, 'prerendered'),
// Optional - The location of index.html
indexPath: path.join(__dirname, 'dist', 'index.html'),
// Required - Routes to render.
routes: [ '/', '/about', '/some/deep/nested/route' ],
// Optional - Allows you to customize the HTML and output path before
// writing the rendered contents to a file.
// renderedRoute can be modified and it or an equivelant should be returned.
// renderedRoute format:
// {
// route: String, // Where the output file will end up (relative to outputDir)
// originalRoute: String, // The route that was passed into the renderer, before redirects.
// html: String, // The rendered HTML for this route.
// outputPath: String // The path the rendered HTML will be written to.
// }
postProcess (renderedRoute) {
// Ignore any redirects.
renderedRoute.route = renderedRoute.originalRoute
// Basic whitespace removal. (Don't use this in production.)
renderedRoute.html = renderedRoute.html.split(/>[\s]+</gmi).join('><')
// Remove /index.html from the output path if the dir name ends with a .html file extension.
// For example: /dist/dir/special.html/index.html -> /dist/dir/special.html
if (renderedRoute.route.endsWith('.html')) {
renderedRoute.outputPath = path.join(__dirname, 'dist', renderedRoute.route)
}
return renderedRoute
},
// Optional - Uses html-minifier (https://github.com/kangax/html-minifier)
// To minify the resulting HTML.
minify: {
collapseBooleanAttributes: true,
collapseWhitespace: true,
decodeEntities: true,
keepClosingSlash: true,
sortAttributes: true
},
// Server configuration options.
server: {
// Normally a free port is autodetected, but feel free to set this if needed.
port: 8001
},
// The actual renderer to use. (Feel free to write your own)
renderer: new Renderer({
// Optional - The name of the property to add to the window object with the contents of `inject`.
injectProperty: '__PRERENDER_INJECTED',
// Optional - Any values you'd like your app to have access to via `window.injectProperty`.
inject: {
foo: 'bar'
},
// Optional - defaults to 0, no limit.
// Routes are rendered asynchronously.
// Use this to limit the number of routes rendered in parallel.
maxConcurrentRoutes: 4,
// Optional - Wait to render until the specified event is dispatched on the document.
// eg, with `document.dispatchEvent(new Event('custom-render-trigger'))`
renderAfterDocumentEvent: 'custom-render-trigger',
// Optional - Wait to render until the specified element is detected using `document.querySelector`
renderAfterElementExists: 'my-app-element',
// Optional - Wait to render until a certain amount of time has passed.
// NOT RECOMMENDED
renderAfterTime: 5000, // Wait 5 seconds.
// Other puppeteer options.
// (See the puppeteer launch options docs)
headless: false // Display the browser window when rendering. Useful for debugging.
})
})
]
}
关键点拆解:
outputDir不设置时默认等于staticDir;indexPath默认是staticDir/index.html(SPA 回退入口)。postProcess在每个路由渲染完成后被调用一次,用于改写 HTML 与输出位置,必须返回 context 对象(或其 Promise)。minify直接透传给 html-minifier(仓库依赖版本^3.5.16),配置项与 html-minifier 的 options 一致。server.port默认自动探测 8000 之后的第一个空闲端口,需要固定时可手动指定。renderer支持换成 jsdom 渲染器,也支持完全自研。
四、插件选项速查表
README 给出了完整的参数表,整理如下:
| Option | Type | Required? | Default | Description |
|---|---|---|---|---|
| staticDir | String | Yes | None | 应用静态服务的根路径 |
| outputDir | String | No | None | 预渲染页面输出目录;未设置时默认 staticDir |
| indexPath | String | No | staticDir/index.html |
SPA 的兜底 index 文件 |
| postProcess | Function(Object context): [Object | Promise] | No | None | 见下文"postProcess 深入"章节 |
| minify | Object | No | None | 使用 html-minifier 压缩产物 HTML |
| server | Object | No | None | 应用服务器配置(见下表) |
| renderer | Renderer Instance or Configuration Object | No | new PuppeteerRenderer() |
用于预渲染的渲染器;不指定则默认 @prerenderer/renderer-puppeteer |
Server Options
| Option | Type | Required? | Default | Description |
|---|---|---|---|---|
| port | Integer | No | 8000 之后的第一个空闲端口 | 应用服务器监听端口 |
| proxy | Object | No | 不代理 | 代理配置,签名与 webpack-dev-server 的 proxy 一致 |
五、postProcess 深入:改写 HTML 与输出路径
postProcess(Object context): Object | Promise 允许你在文件写出之前调整预渲染结果。它按路由逐个调用,收到的 context 对象结构为:
{
// The prerendered route, after following redirects.
route: String,
// The original route passed, before redirects.
originalRoute: String,
// The resulting HTML for the route.
html: String,
// The path to write the rendered HTML to.
// This is null (automatically calculated after postProcess)
// unless explicitly set.
outputPath: String || null
}
你可以修改 context.html 来改变写入文件的内容,也可以修改 context.route 或 context.outputPath 来改变输出位置。改完后必须返回 context 对象,或返回一个 resolve 为 context 的 Promise:
postProcess(context) {
// Remove /index.html from the output path if the dir name ends with a .html file extension.
// For example: /dist/dir/special.html/index.html -> /dist/dir/special.html
if (context.route.endsWith('.html')) {
context.outputPath = path.join(__dirname, 'dist', context.route)
}
return context
}
postProcess(context) {
return someAsyncProcessing(context.html)
.then((html) => {
context.html = html;
return context;
});
}
从源码看 postProcess 的执行时机
在 es6/index.js 的 apply() 实现中,预渲染流水线是严格按序执行的:
- 初始化
Prerenderer并调用renderRoutes(routes); - 兼容 v2 的
postProcessHtml(若存在则逐路由应用); - 调用新版
postProcess钩子(若存在,Promise.all并行处理所有路由); - 校验:
renderedRoutes.every(r => typeof r === 'object'),如果某个路由返回的不是对象,会抛出错误:Rendered routes are empty, did you forget to return the 'context' object in postProcess?——这正是"忘记 return context"的典型报错; - 执行
minify(若配置了minify选项,通过 html-minifier 压缩); - 计算
outputPath:未显式设置时默认为path.join(outputDir || staticDir, route, 'index.html'); - 用
compiler.outputFileSystem逐目录创建并写入文件,最后PrerendererInstance.destroy()收尾。
所以如果你在 postProcess 中改写了 route 或手动设置了 outputPath,最终的文件落点会随之变化;而"路由目录下生成 index.html"的默认行为也解释了为什么每个路由在浏览器里访问时都需要带尾部斜杠(如 http://localhost:8000/about/)。
六、选择渲染器:Puppeteer 还是 jsdom?
可用的渲染器
@prerenderer/renderer-puppeteer:使用 Puppeteer 在 headless Chrome 中渲染页面(仓库的 package.json 直接依赖@prerenderer/renderer-puppeteer ^0.2.0,这是默认渲染器)。@prerenderer/renderer-jsdom:基于 jsdom。极快,但不可靠、无法处理高级用法,可能与部分前端框架和应用不兼容(如程序化 SVG 支持等场景)。
我该用哪个?
README 给出了非常直接的选择建议:
- 选
@prerenderer/renderer-puppeteer:需要预渲染的页面在几百个以内,且追求结果准确(代价是内存消耗大)。 - 选
@prerenderer/renderer-jsdom:需要预渲染成千上万个页面、对质量要求不高,且愿意为高级场景手工绕过各种坑。
@prerenderer/renderer-puppeteer 选项
| Option | Type | Required? | Default | Description |
|---|---|---|---|---|
| maxConcurrentRoutes | Number | No | 0(无限制) | 允许同时渲染的路由数,适合把大批量路由拆成小块处理 |
| inject | Object | No | None | 注入页面全局作用域的对象,必须可被 JSON.stringify;默认挂载到 window['__PRERENDER_INJECTED'] |
| injectProperty | String | No | __PRERENDER_INJECTED |
渲染期间 inject 挂载到的 window 属性名 |
| renderAfterDocumentEvent | String | No | None | 等待 document 上触发指定事件后再渲染(如 document.dispatchEvent(new Event('custom-render-trigger'))) |
| renderAfterElementExists | String (Selector) | No | None | 等待 document.querySelector 检测到指定元素后再渲染 |
| renderAfterTime | Integer (Milliseconds) | No | None | 等待指定毫秒数后再渲染 |
| skipThirdPartyRequests | Boolean | No | false |
自动拦截所有第三方请求(不加载非必要的脚本、样式、字体,加快页面加载) |
| consoleHandler | function(route, message) | No | None | 自定义页面 console.* 处理器;参数一是当前渲染的路由,参数二是 Puppeteer 的 ConsoleMessage 对象 |
| Puppeteer Launch Options | 任意 | No | None | 其余选项会透传给 puppeteer.launch(),如 headless: false |
inject / injectProperty 的实战用法可参考 examples/vanilla-simple/src/main.js:该示例向配置注入了 { foo: 'bar' },然后在页面里读取 window['__PRERENDER_INJECTED'] 并把内容渲染进页面,证明预渲染快照中确实能携带构建期数据。
@prerenderer/renderer-jsdom 选项
| Option | Type | Required? | Default | Description |
|---|---|---|---|---|
| maxConcurrentRoutes | Number | No | 0(无限制) | 允许同时渲染的路由数 |
| inject | Object | No | None | 注入页面全局作用域的对象,必须可被 JSON.stringify;默认挂载到 window['__PRERENDER_INJECTED'] |
| injectProperty | String | No | __PRERENDER_INJECTED |
inject 挂载到的 window 属性名 |
| renderAfterDocumentEvent | String | No | None | 等待 document 触发指定事件后再渲染 |
| renderAfterElementExists | String (Selector) | No | None | 等待 document.querySelector 检测到指定元素后再渲染 |
| renderAfterTime | Integer (Milliseconds) | No | None | 等待指定毫秒数后再渲染 |
三种"等待渲染时机"的选择
vue-router 等 SPA 应用通常用异步数据请求 / 组件挂载后页面才算渲染完成,因此需要告知渲染器"何时截图"。README 提供了三个互斥选项(v3 起不允许同时使用多个 renderAfterX,仅能选其一,目的是避免歧义):
renderAfterDocumentEvent:最推荐。应用渲染完成后派发一个自定义事件,渲染器收到事件才落盘。仓库的 Vue 示例在mounted()钩子里document.dispatchEvent(new Event('render-event'))(见 examples/vue2-webpack-router/src/main.js),同时 webpack 配置里对应设置renderAfterDocumentEvent: 'render-event'(见 examples/vue2-webpack-router/webpack.config.js);vanilla 示例则在每次渲染后同样派发render-event。renderAfterElementExists:等待某个选择器(如'#app')出现在 DOM 中。renderAfterTime:固定等待若干毫秒。README 明确标注 NOT RECOMMENDED——依赖网络通信等高度不确定的耗时操作时,固定延时可能产生不可靠结果。Angular 示例 examples/angular-cli-eject/webpack.config.js 因演示场景简单,使用了renderAfterTime: 500。
七、v2.x 兼容与迁移指南
旧式(位置参数)配置格式
如果你沿用 v2 的风格——把 staticDir、routes、配置对象作为三个位置参数传入——仍然可以工作,但会收到控制台警告,提示迁移到新的对象式配置:
const path = require('path')
const PrerenderSPAPlugin = require('prerender-spa-plugin')
module.exports = {
// ...
plugins: [
new PrerenderSPAPlugin(
// (REQUIRED) Absolute path to static root
path.join(__dirname, 'relative/path/to/static/root'),
// (REQUIRED) List of routes to prerender
[ '/', '/about', '/contact' ],
// (OPTIONAL) Compatible options from v2.
{
// NOTE: Unless you are relying on asynchronously rendered content,
// such as after an Ajax request, none of these options should be
// necessary. All synchronous scripts are already executed before
// capturing the page content.
// Wait until a specific event is fired on the document.
captureAfterDocumentEvent: 'custom-post-render-event',
// This is how you would trigger this example event:
// document.dispatchEvent(new Event('custom-post-render-event'))
// Wait until a specific element is detected with
// document.querySelector.
captureAfterElementExists: '#content',
// Wait until a number of milliseconds has passed after scripts
// have been executed. It's important to note that this may
// produce unreliable results when relying on network
// communication or other operations with highly variable timing.
captureAfterTime: 5000,
// path of index file. By default it's index.html in static root.
indexPath: path.resolve('/dist/path/to/index.html'),
// Manually transform the HTML for each page after prerendering,
// for example to set the page title and metadata in edge cases
// where you cannot handle this via your routing solution.
//
// The function's context argument contains two properties:
//
// - html :: the resulting HTML after prerendering)
// - route :: the route currently being processed
// e.g. "/", "/about", or "/contact")
//
// Whatever is returned will be printed to the prerendered file.
// NOTE: this has been deprecated in favor of the `postProcess` option.
postProcessHtml: function (context) {
var titles = {
'/': 'Home',
'/about': 'Our Story',
'/contact': 'Contact Us'
}
return context.html.replace(
/<title>[^<]*<\/title>/i,
'<title>' + titles[context.route] + '</title>'
)
}
}
)
]
}
这段旧代码透露了一个非常实用的技巧:postProcessHtml 时代人们常拿它来按路由改写 <title>——v3 中同样逻辑迁移到 postProcess 即可。
v3 带来的其他变化
README 的 "Additional Changes" 列出了三点重要差异:
- 不再允许同时使用多个
renderAfterX(旧称captureAfterX),只能二选一,理由同上(消除歧义)。 - 推荐配置格式从
new PrerenderSPAPlugin(staticDir: String, routes: Array<String>, config: Object)改为new PrerenderSPAPlugin({ staticDir: String, routes: Array<String>, ... }),旧格式暂时仍可用。 - 默认渲染器不再是 PhantomJS,替换为 Puppeteer;开发自己的渲染器也很简单(渲染器是插件化的)。此外
prerender-spa-plugin现在基于 prerenderer 构建,因此多数 bug 应反馈到 prerenderer 仓库。
这些兼容逻辑在 es6/index.js 的构造函数中有完整实现:构造函数会遍历位置参数(字符串→staticDir,数组→routes,对象→配置),并分别对 captureAfterDocumentEvent、captureAfterElementExists、captureAfterTime 输出重命名警告、自动映射到 renderAfterX 后再合并进默认渲染器选项。若检测到 postProcessHtml,同样会输出迁移提示。
八、Vue.js 注意事项
如果 Vue 预渲染遇到问题,README 建议给根应用元素加上 data-server-rendered="true" 属性(对应 Vue SSR hydration 机制)。这会告诉 Vue"当前页面已经渲染过",从而增量更新(patch)现有树而不是整棵重新渲染。你可以通过 postProcess 注入该属性,也可以在预渲染之前用 renderAfterDocumentEvent 配合 JS 操作 DOM 来添加。
仓库的 Vue 2 示例(examples/vue2-webpack-simple、examples/vue2-webpack-router)均采用标准 <div id="app"></div> 挂载点,并在生产构建分支中注册插件,可供对照参考。
九、常见问题与故障排查
JS 在预渲染前没有执行?
如果你有依赖 <body> 存在的代码(几乎所有人都有),请把它放到 DOMContentLoaded 回调里执行。否则你会发现 prerender-spa-plugin 输出的是 JS 尚未运行时的空页面:
document.addEventListener('DOMContentLoaded', function () {
// your code
})
例如 Vue 挂载到 <body> 中的 <div id="app"> 时:
const root = new Vue({
// ...
})
document.addEventListener('DOMContentLoaded', function () {
root.$mount('#app')
})
这一条在仓库的测试资产 test/assets/single-route/index.html 中得到了印证:测试页面在 DOMContentLoaded 回调里把 document.body.innerHTML 改写为 Render Successful!,以此验证"JS 确实在快照前执行了"。
内联样式导致重复的 style 标签?
如果依赖内联 CSS(即没有从 bundle 中抽取 CSS),预渲染产物可能出现重复的 style 标签。README 建议:
- 用 extract-text-webpack-plugin 把 CSS 抽取为独立文件;
- 再通过 html-webpack-plugin 把 CSS 注入回
template.html,或直接以外部 CSS 文件方式引用。
无论哪种方式,JS 里都不会残留多余样式。
其他注意点(Caveats)
- 出于显而易见的原因,只有使用 HTML5 history API 路由的 SPA 才支持预渲染;
index.html#/hash/route形式的 hash 路由不适用。 - 你使用的客户端渲染库应当至少能替换(replace)或 diff 掉服务端渲染的内容:
- Vue.js 1:根组件使用
replace: false; - Vue.js 2:确保根组件 id 与它替换的预渲染元素 id 相同,否则会出现内容重复。
- Vue.js 1:根组件使用
十、从源码看完整执行流水线
- index.js 是运行时入口包装器:Node 8+ 直接加载 es6/index.js(原生
async/await),更旧的 Node 版本则加载es5-autogenerated/index.js(经 Babel 转译、面向 Node 4+)。 - es6/index.js 的
apply(compiler)是核心:对 webpack 4 挂compiler.hooks.afterEmit.tapAsync,对旧版 webpack 挂compiler.plugin('after-emit')。回调里依次执行:初始化Prerenderer→renderRoutes(routes)→ 兼容层postProcessHtml→postProcess→ 对象校验 →minify→ 计算outputPath→mkdirp+writeFile写出(全部经由compiler.outputFileSystem,与 webpack 输出目录保持一致),任一环节出错都会向compilation.errors推入Unable to prerender all routes!错误。
这条流水线解释了你在配置中看到的每个选项最终如何生效,也是排查"预渲染失败/文件没生成"时最值得先看的代码。
十一、仓库示例导航
官方在 examples/ 目录下提供了五个框架示例,覆盖不同构建体系:
- examples/vanilla-simple —— 原生 JS + webpack 3,演示 3 条静态路由
- examples/vue2-webpack-simple —— Vue 2 + webpack 4 简单模板
- examples/vue2-webpack-router —— Vue 2 + vue-router(history 模式)
- examples/create-react-app —— Create React App + react-app-rewired(插件配置写在 config-overrides.js,仅在生产环境注入插件)
- examples/angular-cli-eject —— Angular CLI eject 后的 webpack 配置(插件位于 webpack.config.js 的 plugins 段)
每个示例的 README 都给出了 npm install && npm run build 的构建流程,构建后在 dist 目录内用 http-server 启动(注意带尾部斜杠访问,如 http://localhost:8000/about/),即可验证"禁用 JavaScript 也能看到渲染好的页面"。若使用了 vue-router / 多页面,编辑各示例 webpack 配置中 new PrerenderSPAPlugin 的 routes 数组即可扩展预渲染范围。
十二、总结
预渲染是在"SSR 太重、纯 SPA 太裸"之间的一条务实路径:构建期用 headless 浏览器跑一遍应用、把每个路由固化成静态 HTML,既保留 SPA 的交互能力,又让爬虫、分享卡片和弱 JS 环境拿到完整内容。掌握本文覆盖的内容——staticDir/routes 最小配置、postProcess 输出改写、Puppeteer/jsdom 渲染器取舍、renderAfterDocumentEvent 等时机控制、Vue hydration 细节以及 v2 迁移路径——你就能在生产 webpack 项目中稳定落地预渲染能力。