5

I am having a prop which takes either a function or Component. So I want to differentiate by checking types of prop whether it's a component or function. I am at present using following one. This may not work in prod when code gets obfuscated. Wanted to know better solution?

let isSvelteComponent = component => {
    return (
      typeof component !== "undefined" &&
      component.__proto__.name === "SvelteComponentDev"
    );
  };

2 Answers 2

3

I would argue that, loosely speaking, any function can potentially be a valid Svelte component:

<script>
    import B from './B.svelte'

    const C = function(opts) {
        return new B(opts)
    }
</script>

<B />   

<C />

REPL

As such, there isn't really a completely reliable way to tell appart a Svelte component from a regular function.

In your case, if the Svelte component and the function have different meaning and should be handled differently, maybe they should be passed through different props? That would allow to know for sure what is what, and what it is intended for.

1

I was able to fix this by checking prototype like following

import { SvelteComponent } from "svelte";
let isSvelteComponent = component => {
   return SvelteComponent.isPrototypeOf(component);
};
4
  • Seems to be working! Have you encountered edge cases where this test might fail? For the record, I use return Object.prototype.isPrototypeOf.call(SvelteComponent, component);, as per my ESLint recommendations!
    – DSav
    Jun 3, 2020 at 14:36
  • 2
    For the record, this kind of check is lost through code minification. To this day, I don't have a reliable way to differentiate a Svelte component.
    – DSav
    Mar 3, 2021 at 1:04
  • @DSav that thing about code minification is scary. could you explay why that happens?
    – Paolo
    Apr 12, 2022 at 16:55
  • 1
    @Paolo I'm not sure if "code minification" is actually what is going on, to be honest. I didn't dig much into this since this reply. However, from what I remember, there was a difference that made this trick work in development, but not in production (I think I was using this in a Meteor project). Please don't take my word for it and try it out yourself. I'm a more experienced programmer now and maybe I would find out why it didn't work out then, but I don't use this trick anymore, I'm sorting my components differently.
    – DSav
    Apr 13, 2022 at 12:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.