Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

⚙️ Crank.js with tagged templates

License

NotificationsYou must be signed in to change notification settings

aidenybai/hacky-js

Repository files navigation

<2kb tagged template alternative for Crank.js

Hacky is something that I've always wanted. I've used React previously, but I findhooks too magical and JSX afinicky process that requires a build step.

When I discovered Crank.js, I fell in love because of how intuitive it was to understand. Imagine Hacky asCrank.js with tagged templates, but with a lightweight core and simplistic API.

If you're looking for something a bit more comprehensive, check outMillion — Virtual DOM into the future! 💥🦁✨

-Aiden (@aidenybai)

random.cat API Example

Below is an implementation of arandom.cat API fetcher example using Hacky (Live Demo).

import{html,render}from'https://cdn.skypack.dev/hacky';constfetchCat=async(url='https://aws.random.cat/meow')=>{constres=awaitfetch(url);const{ file}=awaitres.json();returnfile;};function*Cats({ width, height}){const[cats,setCats]=this.createState([]);const[message,setMessage]=this.createState('Fetch cat image');const[disabled,setDisabled]=this.createState(false);constaddCat=async()=>{setMessage('Fetching...');setDisabled(true);try{constnewCat=awaitfetchCat();setCats([...cats(),newCat]);setMessage('Fetch cat image');setDisabled(false);}catch(err){console.error(err);setMessage('Failed to fetch. Retrying...');setTimeout(()=>addCat(),1000);}};while(true){constcatImages=cats().map((cat)=>html`<imgkey=${cat}src=${cat} width=${width} height=${height}/>`,);yieldhtml`<buttondisabled=${disabled()}onClick=${addCat}>${message()}</button><div>${catImages}</div>    `;}}render(html`<${Cats}width=${100} height=${100}/>`,document.body);

render() function has a standard interface that is used in many Virtual DOM libraries. First argument is a Virtual DOM to render, and the second one is a DOM node that will be used as the live DOM reference.

html tagged templates can produce Virtual DOM nodes, which define your DOM view.

this.createState() function will instantiate a new state reference, in which you can mutate by destructuring the getter (index0) and setter (index1).

Acknowledgments

Hacky takes heavy inspiration fromCrank.js, and depends onMillion. Feel free to check them out if you interested in an alternative library to use.

License

Million isMIT-licensed open-source software byAiden Bai.


[8]ページ先頭

©2009-2026 Movatter.jp