solidjs / templates

Vite + solid templates
447 stars 117 forks source link

Check if root element is present instead of unsafe casting to HTMLElement #83

Closed aminnairi closed 1 year ago

aminnairi commented 1 year ago

It would be great to warn the user in the console if the root element is not present with a friendly message.

For now, the error that a user might have whenever the root element is not found (missing div, wrong id, mispelled, ...) is the following.

Uncaught TypeError: Cannot read properties of null (reading 'firstChild')

Which is not the friendliest error message in the world, and I understand if this is something that can and should be userland.

Instead, what I would suggest would be to add some more code in the index.tsx file in order to check for whether the element is indeed present or not.

/* @refresh reload */
import { render } from "solid-js/web"

import "./index.css"
import Main from "./main"

const rootElement = document.getElementById("root")

if (!(rootElement instanceof HTMLDivElement)) {
  throw new Error("Root element not found. Did you forget to add it to your index.html? Or maybe the id attribute got mispelled?")
}

render(
  () => <Main />,
  rootElement
)

This has three benefits:

It would be nice to have it in the templates to enhance the user experience since this is not something that will add too much overhead at runtime (since it is run once per page load) and can be nice for spotting silly mistakes.

amoutonbrady commented 1 year ago

Hey! Thanks for filling out the issue.

That is a nice idea. I'll refactor the templates to add a message if the root isn't found only in dev :)