Skip to main content
Basic Svelte
Introduction
Reactivity
Props
Logic
Events
Bindings
Classes and styles
Actions
Transitions
Advanced Svelte
Advanced reactivity
Reusing content
Motion
Advanced bindings
Advanced transitions
Context API
Special elements
<script module>
Next steps
Basic SvelteKit
Introduction
Routing
Loading data
Headers and cookies
Shared modules
Forms
API routes
$app/state
Errors and redirects
Advanced SvelteKit
Hooks
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion

module スクリプトブロックからエクスポートされたものはすべてモジュール自体からのエクスポートになります。stopAll 関数をエクスポートしましょう:

AudioPlayer
<script module>
	let current;

	export function stopAll() {
		current?.pause();
	}
</script>

App.sveltestopAll をインポートすることができます…

App
<script>
	import AudioPlayer, { stopAll } from './AudioPlayer.svelte';
	import { tracks } from './tracks.js';
</script>
<script lang="ts">
	import AudioPlayer, { stopAll } from './AudioPlayer.svelte';
	import { tracks } from './tracks.js';
</script>

…さらにそれをイベントハンドラで使うことができます。

App
<div class="centered">
	{#each tracks as track}
		<AudioPlayer {...track} />
	{/each}

	<button onclick={stopAll}>
		stop all
	</button>
</div>

default export は使うことはできません、なぜならコンポーネント自体が default export だからです。

Edit this page on GitHub

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<script>
	import AudioPlayer from './AudioPlayer.svelte';
	import { tracks } from './tracks.js';
</script>
 
<div class="centered">
	{#each tracks as track}
		<AudioPlayer {...track} />
	{/each}
</div>
 
<style>
	.centered {
		display: flex;
		flex-direction: column;
		height: 100%;
		justify-content: center;
		gap: 0.5em;
		max-width: 40em;
		margin: 0 auto;
	}
</style>