developit / htm

Hyperscript Tagged Markup: JSX alternative using standard tagged templates, with compiler support.
Apache License 2.0
8.72k stars 170 forks source link

Easier for JSX users to spot missing `${...}` #208

Open orangemug opened 3 years ago

orangemug commented 3 years ago

I've been using htm for a while now (it's awesome btw), every once in a while though I switch back from a project using JSX and end up writing <Avatar /> instead of <${Avatar} /> or <div className={classnames(...)} /> instead of <div className=${classnames(...)} />.

It is sometimes hard to spot why something's failing, because it fails quietly, doesn't throw an error or obvious warning. I believe (and please correct me) the library could check for attributes starting with /^{/ or elements starting with /^[A-Z]/ and warn the user about their potential error.

Because you're very unlikely to have an element with either of the above, it seems like something that could potentially be enabled by default. Or available by default in a developer build.

There is a little demo showing the error at https://github.com/orangemug/htm-suggestion.

Thoughts?

developit commented 3 years ago

Hi @orangemug! Sorry for the super slow reply. Here's a Preact plugins that detects these typos and throws an exception right at the callsite:

import { options } from 'preact';

let old = options.vnode;
options.vnode = vnode => {
  let props = vnode.props;
  if (props) for (let i in props) {
    let v = props[i];
    if (i === 'children' || typeof v !== 'string') continue;
    if (v[0] == '{' && v[v.length-1] === '}') throw Error(`Missing $ in prop value: ${i}=\${ }`);
  }
  if (old) old(vnode);
};
orangemug commented 2 years ago

Hey thanks @developit sorry this got lost in the GH notifications. I think this would be really cool to get into something you could import from the skypack (or similar). My go to tool is preact/htm/skypack but the <Avatar /> vs <${Avatar} /> was super frustrating at first it took a long time of to train my fingers to not make mistakes, on occasion my fingers still fail me 😁

If I could do something like the following, it'd be freaking awesome for putting together demos/mockups.

import htm from 'https://cdn.skypack.dev/htm/debug';

Either way, thanks for the plugin I'll try it out tomorrow. Thanks for htm can't stress enough how much it's made my life more pleasant.