I have a Error.svelte component which has a <script context="module">
containing a writable store and a exported 'addError' function, altering the store content.
<script context="module">
import {get, writable} from "svelte/store";
let errorStore = writable([])
export function addError(error) {
let errors = get(errorStore)
errors.push(error)
errorStore.set(errors)
throw error
}
</script>
<script>
import Error, {addError} from './Error.svelte'
import DifferentComp from './DifferentComp.svelte'
</script>
<Error />
<button on:click={() => addError(new Error('error message'))}>
addError() from App
</button>
<DifferentComp />
<script>
import {addError} from './Error.svelte'
</script>
<button on:click={() => addError(new Error('error message'))}>
addError() from DifferentComp
</button>
When importing and running this function from the component works fine, but from App.svelte I get the error message "Error: 'target' is a required option"
See this REPL for a live demo
Is there a difference when importing from App.svelte to importing from another component and there's a reason for the error, or is this simply a bug?
The problem is that in your App.svelte
, you are shadowing the global Error
constructor with the imported Error
svelte component. Inside DifferentComp
new Error()
means "create an error", whereas in App.svelte
it means "create an instance of the Error component". Rename the default import to something else and it works.