vatro / svelthree

Create three.js content using Svelte components.
https://svelthree.dev
MIT License
482 stars 15 forks source link

Examine `$capture_state()` availability #198

Closed vatro closed 1 year ago

vatro commented 1 year ago

I ran into an issue with svelthree-test-scenes while using $capture_state() to get components props where ~comp.$capture_state() was first available onMount of the top-parent (+page) when previewing a built SvelteKit project~ $capture_state() wasn't available in the build-preview, though in dev-mode it was available. This needs to be deeper examined / nailed down.

I order to move forward, I've implemented the comp.state() method which turns out to be actually better compared to using comp.$capture_sate() (which cannot be used in production anyway!), because:

RESOLVED: $capture_state() cannot be used in production! (see comment below)

vatro commented 1 year ago

Ok,

$capture_state(): void;
$inject_state(): void;

are defined for SvelteComponentDev, so should be available only in dev-mode, see: https://github.com/sveltejs/svelte/blob/670f4580568fe8ea31097981ba2d59c33daf0725/src/runtime/internal/dev.ts#L164-L205

means also: SVELTE-REPL must be operating in dev-mode per default, because there it's always available. When the JS-Output switch is turned to dev: true, we can see:

$$self.$capture_state = () => ({ MyComponent, onMount, tick, comp });

$$self.$inject_state = $$props => {
  if ('comp' in $$props) $$invalidate(0, comp = $$props.comp);
};

which is gone if the switch is turned to dev: false. But the compilation itself seems to always be in dev-mode, it doesn't matter where the switch is, that's only for output-code examination.

It's also gone if we switch the JS output to ssr in dev-mode.

SURE IS: we cannot use $capture_state() in production, so it's good that I've implemented state() 👍, there is / was actually no way around it without using accessors and without creating own getters for every prop.

REMARK: I think $capture_state() and $inject_state() should also get a Cannot be used in production! warning JSDoc because they always appear in the autocomplete-menu after a user puts a dot behind a component-reference, together with $set, $on and $destroy which are always available, I find this pretty misleading:

image image

$$prop_def has such a warning: image