html-renderer-webpack-plugin4.0.18 • Public • Published
A webpack plugin for rendering static html pages.
npm install --save-dev html-renderer-webpack-plugin
yarn add --dev html-renderer-webpack-plugin
;;...configoutputpublicPath = '/';...configplugins;
This plugin provides a server-like environment for rendering static (React) html pages. It is useful for serverless environments as a static site generator.
Pages are rendered from a supplied
paths: string array that should include your supported (static) routes. It might be useful to import these from your router configuration.
The plugin is supplied an async renderer function that, for example, renders your pages using
<div id="root> tag.
The renderer function should be of type:
type RendererArgs =assets:key: string: string;;compilationAssets:key: string: import"webpack-sources"CachedSource;;filename: string;path: string;publicPath: string;stats: ReturnType<import"webpack"Stats"toJson">;;args: Partial<RendererArgs>) string | Promise<string>;
An object with all of webpack's compiled asset filenames, seperated by their file extensions into arrays.
The raw contents of webpack's compilation.assets.
A string of the current path's filename.
A string of the current path. This is useful for routing.
The public path prefix as set in webpack's
stats.toJson() object. This is useful for webpack-flush-chunk.
Because your renderer function typically imports your
<App />, you probably need babel. The easiest way is to run your webpack config through babel with
webpack --config webpack.config.babel.js.
Working with Hot Reloading
- In your
rendererfunction, require your main React component instead of importing:
const App = require('src/components/App').default
- After watch mode recompilation,
require.cachewill be invalidated and using
requirewill result in updated code.
A typical feature of a dev environment includes some hot module replacement. When using
html-renderer-webpack-plugin, you might want to ensure that when the client bundle gets hot-updated, also the HTML files are rendered with the content.
By default, when using
import to require you application code, for example
import App from 'src/components/App, the resulting module will be cached in the node process. Thus, after recompiling your html files after a webpack HMR update, the html file will still contain the old version, because it is cached in the
To overcome this limitation, this plugin hooks into Webpack's
watchRun hook, that runs in watch mode when files change. It will then invalidate every require used in changed files from the
require.cache. Thus, if you use
const App = require('src/components/App').default inside your renderer function, it will be freshly required the next time the HTML file is created. This will result in "hot-reloading" working properly for statically rendered content.
You can disable this behaviour by supplying the
hot: false option in the plugin constructor.