htmlhammer icon indicating copy to clipboard operation
htmlhammer copied to clipboard

Support serverside usage in nodejs

Open kleutzinger opened this issue 2 years ago • 4 comments

I figured out a sort of hacky way to use hammerjs in nodejs by using the library jsdom. Hammer expects there to be some global browser objects in order to do stuff. I wonder if there is a better way to do this?

import { JSDOM } from "jsdom";
global.document = new JSDOM("").window.document;
global.HTMLElement = global.document.defaultView.HTMLElement;
import * as hammer from "htmlhammer";
Object.assign(global, hammer);

let items = [{ value: 1 }, { value: 2 }];

const mydiv = div(
  { style: { color: "red" } },
  h1("I am the title"),
  a({ href: "#" }, "Click me!"),
  table(tr({ $for: items }, (item) => td(item.value))),
);

// to get raw html string, do
mydiv.outerHTML;

export default mydiv;

I like hammer's api, but if there's a better library to let me gen html serverside like this, let me know.

kleutzinger avatar Oct 05 '23 23:10 kleutzinger

relevant blogpost: https://dustinpfister.github.io/2018/01/11/nodejs-jsdom/

kleutzinger avatar Oct 05 '23 23:10 kleutzinger

i'll probably go with this

https://github.com/ohanhi/hyperscript-helpers

kleutzinger avatar Oct 06 '23 00:10 kleutzinger

Hi,

I was thinking of adding some sort of SSR support(even though this may not be your real need but maybe just templating) and I will probably add it when I catch some spare time :) For testing purposes I used basichtml as a browser DOM implementation but this dependency will be replaced in the near future. At the time of making I considered jsdom but it seemed too heavy for what I needed. TBH, I haven't tried htmlhammer on the backend side yet but after your post I may give it a shot. I will look at you proposal when my daily work allows it.

I am glad you liked htmlhammer, thanks :)

vsmid avatar Oct 06 '23 06:10 vsmid

@kleutzinger I forgot to mention something, take a look at this GitHub account -> https://github.com/WebReflection. I think you will find everything you need here :)

vsmid avatar Oct 06 '23 14:10 vsmid