在单页面应用程序中预渲染静态 HTML。
Flexible, framework-agnostic static site generation for sites and SPAs built with webpack.
--- --- ## About prerender-spa-plugin **:point_right: This is the stable `3.x` version of `prerender-spa-plugin` based on puppeteer. If you're looking for the (now-deprecated) `2.x` version, based on PhantomJS, take a look at the `v2` branch.** The goal of this plugin is to provide a simple prerendering solution that is easily extensible and usable for any site or single-page-app built with webpack. Plugins for other task runners and build systems are planned. ## Examples Framework-specific examples can be found in the `examples/` directory. - [Vanilla JS](examples/vanilla-simple) - [Vue.js 2 Simple](examples/vue2-webpack-simple) - [Vue.js 2 Router](examples/vue2-webpack-router) - [React (Create React App)](examples/create-react-app) - [Angular (Angular CLI + Eject)](examples/angular-cli-eject) ### Basic Usage (`webpack.config.js`) ```js 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' ], }) ] } ``` ### Advanced Usage (`webpack.config.js`) ``` … ``` ### v2.x Compability Most usages of `prerender-spa-plugin` v2.x should be compatible with v3.x. The exception being advanced configuration options that controlled PhantomJS. These have been replaced by pluggable renderers with their own specific configuration options. If you use this format, you will be greeted with a warning prompting you to migrate to the new object-based configuration format, but it should still function for the time being. ``` … ``` #### Additional Changes - It is no longer possible to use multiple `renderAfterX` (`captureAfterX`) options at the same time. Only one may be selected. The reason for this removal is to prevent ambiguity. - The recommended configuration format has changed from `new PrerenderSPAPlugin(staticDir: String, routes: Array, config: Object)` to ```javascript new PrerenderSPAPlugin({ staticDir: String, routes: String, ... }) ``` in order to reduce ambiguity. The old format still works for the time being. - The default renderer is no longer PhantomJS. It has been replaced with [puppeteer](https://github.com/GoogleChrome/puppeteer). It is fairly simple to develop your own renderer as well. An alternate [jsdom](https://github.com/tmpvar/jsdom)-based renderer is available at [@prerenderer/renderer-jsdom](https://www.npmjs.com/package/@prerenderer/renderer-jsdom). - `prerender-spa-plugin` is now based on [prerenderer](https://github.com/Tribex/prerenderer). Accordingly, most bugs should be reported in that repository. ## What is Prerendering? Recently, SSR (Server Side Rendering) has taken the JavaScript front-end world by storm. The fact that you can now render your sites and apps on the server before sending them to your clients is an absolutely *revolutionary* idea (and totally not what everyone was doing before JS client-side apps got popular in the first place...) However, the same criticisms that were valid for PHP, ASP, JSP, (and such) sites are valid for server-side rendering today. It's slow, breaks fairly easily, and is difficult to implement properly. Thing is, despite what everyone might be telling you, you probably don't *need* SSR. You can get almost all the advantages of it (without the disadvantages) by using **prerendering.** Prerendering is basically firing up a headless browser, loading your app's routes, and saving the results to a static HTML file. You can then serve it with whatever static-file-serving solution you were using previously. It *just works* with HTML5 navigation and the likes. No need to change your code or add server-side rendering workarounds. In the interest of transparency, there are some use-cases where prerendering might not be a great idea. - **Tons of routes** - If your site has hundreds or thousands of routes, prerendering will be really slow. Sure you only have to do it once per update, but it could take ages. Most people don't end up with thousands of static routes, but just in-case... - **Dynamic Content** - If your render routes that have content that's specific to the user viewing it or other dynamic sources, you should make sure you have placeholder components that can display until the dynamic content loads on the client-side. Otherwise it might be a tad weird. ## Available Renderers - `@prerenderer/renderer-puppeteer` - Uses [puppeteer](https://github.com/GoogleChrome/puppeteer) to render pages in headless Chrome. - `@prerenderer/renderer-jsdom` - Uses [jsdom](https://npmjs.com/package/jsdom). Extremely fast, but unreliable and cannot handle advanced usages. May not work with all front-end frameworks and apps. ### Which renderer should I use? **Use `@prerenderer/renderer-puppeteer` if:** You're prerendering up to a couple hundred pages and want accurate results (bye-bye RAM!). **Use `@prerenderer/renderer-jsdom` if:** You need to prerender thousands upon thousands of pages, but quality isn't all that important, and you're willing to work around issues for more advanced cases. (Programmatic SVG support, etc.) ## Documentation ### Plugin Options | Option | Type | Required? | Default | Description | |-------------|-------------------------------------------|-----------|---------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | staticDir | String | Yes | None | The root path to serve your app from. | | outputDir | String | No | None | Where the prerendered pages should be output. If not set, defaults to staticDir. | | indexPath | String | No | `staticDir/index.html` | The index file to fall back on for SPAs. | | postProcess | Function(Object context): [Object \| Promise] | No | None | See the [Using the postProcess Option](#using-the-postprocess-option) section. | | minify | Object | No | None | Minifies the resulting HTML using [html-minifier](https://github.com/kangax/html-minifier). Full list of options available [here](https://github.com/kangax/html-minifier#options-quick-reference). | | server | Object | No | None | App server configuration options (See below) | | renderer | Renderer Instance or Configuration Object | No | `new PuppeteerRenderer()` | The renderer you'd like to use to prerender the app. It's recommended that you specify this, but if not it will default to `@prerenderer/renderer-puppeteer`. | #### Server Options | Option | Type | Required? | Default | Description | |--------|---------|-----------|----------------------------|----------------------------------------| | port | Integer | No | First free port after 8000 | The port for the app server to run on. | | proxy | Object | No | No proxying | Proxy configuration. Has the same signature as [webpack-dev-server](https://github.com/webpack/docs/wiki/webpack-dev-server#proxy) | #### Using The postProcess Option The `postProcess(Object context): Object | Promise` function in your renderer configuration allows you to adjust the output of `prerender-spa-plugin` before writing it to a file. It is called once per rendered route and is passed a `context` object in the form of: ```javascript { // 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 } ``` You can modify `context.html` to change what gets written to the prerendered files and/or modify `context.route` or `context.outputPath` to change the output location. You are expected to adjust those properties as needed, then return the context object, or a promise that resolves to it like so: ```javascript 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; }); } ``` #### Vue.js Notes If you are having issues prerendering with Vue.js, try adding the [`data-server-rendered="true"`](https://ssr.vuejs.org/guide/hydration.html) attribute to your root app element. This will cause Vue to treat your current page as an already-rendered app and update it rather than completely rerendering the whole tree. You can add the attribute using `postProcess` or by manipulating the DOM with JavaScript prior prerendering with `renderAfterDocumentEvent`. --- ### `@prerenderer/renderer-puppeteer` options | Option | Type | Required? | Default | Description | |------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------|-----------|------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | maxConcurrentRoutes | Number | No | 0 (No limit) | The number of routes allowed to be rendered at the same time. Useful for breaking down massive batches of routes into smaller chunks. | | inject | Object | No | None | An object to inject into the global scope of the rendered page before it finishes loading. Must be `JSON.stringifiy`-able. The property injected to is `window['__PRERENDER_INJECTED']` by default. | | injectProperty | String暂无开放 Issues,或尚未同步最近议题。