使用 viperHTML 进行服务器端呈现
Server Side Rendering with viperHTML
我正在开发一个 Symfony 应用程序,并且刚刚使用 https://github.com/spatie/server-side-rendering 获得了适用于 JS 的 SSR。到目前为止,我只使用 "readymade" React 的 SSR 解决方案,但目前我正在尝试使用 hyperHTML/viperHTML 并且面临一些到目前为止我无法通过查看可用解决方案解决的问题docs/examples.
我当前的测试片段是这样的:
const viperHTML = require('viperhtml');
class Component extends viperHTML.Component {
constructor(props) {
super();
this.props = props;
}
render() {
return this.html`
<h1>Hello, ${this.props.name}</h1>`;
}
}
console.log(new Component({ name: 'Joe' }).render().toString());
这里的问题是,如果不显式调用 render()
,我将得不到任何输出。查看一些官方示例,这不是必需的,至少 Component
不需要。例如,我已经尝试在构造函数中使用 setState()
,但没有区别。
此外,如果不同时使用 console.log()
和 toString()
,我也没有输出。这是出乎意料的。我知道 toString()
在这里可能是必要的(如果没有它,将呈现 <buffer />
),但是 console.log()
看起来很奇怪。当然,这可能与 viperHTML 完全无关。但是实例化组件是我认为唯一必要的事情。
我还不清楚如何编写 isomorphic/universal 组件,即一个包含标记、事件处理程序等的文件在服务器上呈现,然后在客户端上混合。当我根据文档 (https://viperhtml.js.org/hyperhtml/documentation/#essentials-6) 添加内联事件处理程序时,它实际上内联到呈现的标记中,这不是我想要的。 我检查了 hypermorphic 和 viperNews 应用程序,但到目前为止并没有真正帮助我。
如果有帮助,您可以read viperHTML tests查看如何使用组件。
The thing here is that without explicitly calling render() I get no output.
组件旨在用于在服务器端或客户端呈现布局。这意味着如果您将组件实例传递给 hyper/viperHTML 视图,您不必担心调用任何东西,它已经为您完成。
const {bind, Component} = require('viperhtml');
class Hello extends Component {
constructor(props) {
super().props = props;
}
render() {
return this.html`<h1>Hello, ${this.props.name}</h1>`;
}
}
console.log(
// you need a hyper/viperHTML literal to render components
bind({any:'ref'})`${Hello.for({ name: 'Joe' })}`
// by default you have a buffer to stream in NodeJS
// if you want a string you need to use toString()
.toString()
);
由于 NodeJS 默认流缓冲区,因此 viperHTML 生成的任何布局都将是缓冲区,因此可以在组合时进行流式传输(即使用 Promises 作为插值)。
It's also not clear to me yet how I can write an isomorphic/universal component, i.e. one file which has the markup, event handlers etc., gets rendered on the server and then hydrated on the client.
hyperHTML 的原始版本有一个名为 adopt()
的方法,其目的是通过相同的模板文字来滋润活动节点。
虽然 viperHTML 有一个 viperhtml.adoptable = true
开关来呈现可采用的内容,但 hyperHTML adopt
功能仍然 not quite there yet 因此,暂时,您可以轻松地在 SSR 和FE,但是您需要在 SSR 页面登陆后接管客户端,或者第一次做出不同的反应并远距离接管客户端。
这不是最佳选择,但我担心补水位,做得好,很费时间,我还没有找到这样的时间来完成它并运送它。
此时可能是 hyperHTML v3。
我希望这个回答有助于理解 viperHTML 的工作原理以及当前状态。