如果你想使用 static-site-generator-webpack-plugin,你首先需要使用 webpack bundle.js 构建一个包,它导出一个带有以下参数的渲染函数。
-
locals 具有各种页面元数据的对象,例如title 进入组件参数(传统上被认为是模板变量)。
-
callback 一个 nodejs 样式 (err, result) 回调,您将使用呈现的 html 作为 result 的值来调用它
例如
// entry.js, compiled to bundle.js by webpack
module.exports = function render(locals, callback) {
callback(null,
'<html>' + locals.greet + ' from ' + locals.path + '</html>');
};
在这个函数中,您将实例化您的组件(如果需要,可以通过 React Router)并使用ReactDOMServer.renderToString() 渲染它们。
然后,您将在 StaticSiteGeneratorPlugin 的实例化中将编译后的 bundle.js 指定为 bundle,并在 paths 和 locals 中指定包含上述元数据值的对象。
var paths, locals; // compute paths from metadata files or frontmatter
module.exports = {
entry: {
bundle: './entry.js' // build bundle.js from entry.js source
},
...,
plugins: [
new StaticSiteGeneratorPlugin('bundle', paths, locals)
]
}
您为webpack.config.js 中的locals 指定的键将出现在每次调用render(locals, callback) 的locals 参数中。它们将与插件提供的path、assets 和webpackStats 键合并。
如果您想在渲染后将 javascript 代码加载到您的页面中,您可以在 webpack 配置中编译一个额外的 page.js 条目,该条目以典型方式调用 ReactDOM.render(),然后将该包加载到由发出的 script 标记中在bundle.js 中的render(locals, callback) 函数中(上图)。确保 page.js 将组件安装到 DOM 中的相同位置,因为它们在由 entry.js 呈现时(您可能会在父元素上设置 id 属性)。您还需要确保任何位置(即路线路径)因变量在两种环境中都对齐。
查看Gatsby 的源代码,它也使用了这个插件。您还可以查看Phenomic 的源代码以了解替代方法。