
よっしー
こんにちは。よっしーです(^^)
今日は、SvelteKitのリファレンスについて解説しています。
背景
SvelteKitのリファレンスについて調査する機会がありましたので、その時の内容を備忘として記事に残しました。
@sveltejs/kit
BeforeNavigate
BeforeNavigate
コールバックに渡される引数について解説します。
interface BeforeNavigate extends Navigation {
cancel: () => void;
}
このインターフェースの重要なポイント:
Navigation
インターフェースを継承しています
- これにより、ナビゲーションに関する基本的な情報(from, to, typeなど)が含まれます
cancel: () => void
- ナビゲーションを中止するための関数
- この関数を呼び出すと、開始しようとしているナビゲーションがキャンセルされます
使用例
import { beforeNavigate } from '$app/navigation';
beforeNavigate((navigation) => {
// 未保存の変更があるかチェック
if (hasUnsavedChanges()) {
// ユーザーに確認
const shouldProceed = confirm('未保存の変更があります。本当に移動しますか?');
// キャンセルが選択された場合、ナビゲーションを中止
if (!shouldProceed) {
navigation.cancel();
}
}
// ナビゲーション情報のログ
console.log('From:', navigation.from);
console.log('To:', navigation.to);
console.log('Type:', navigation.type);
});
このインターフェースは、ナビゲーション前の処理(例:フォームの検証、未保存データの確認、ユーザーへの確認など)を実装する際に使用されます。
Builder
Builder インターフェースの解説です。これはアダプターのadapt
関数に渡されるオブジェクトで、アプリケーションの適応に必要な様々なメソッドとプロパティを含んでいます。
主要なプロパティとメソッド:
- 基本的なファイル操作:
// ロギング
log: Logger; // コンソールへのメッセージ出力
// ディレクトリ操作
rimraf: (dir: string) => void; // ディレクトリの再帰的削除
mkdirp: (dir: string) => void; // ディレクトリの再帰的作成
- 設定とルート情報:
config: ValidatedConfig; // 解決済みのsvelte.config.js
prerendered: Prerendered; // プリレンダリングされたページと資産の情報
routes: RouteDefinition[]; // 全ルートの配列
- ファイル生成と書き込み:
// クライアントファイルの書き込み
writeClient: (dest: string) => string[];
// サーバーファイルの書き込み
writeServer: (dest: string) => string[];
// プリレンダリングファイルの書き込み
writePrerendered: (dest: string) => string[];
// フォールバックページの生成
generateFallback: (dest: string) => Promise<void>;
// 環境変数モジュールの生成
generateEnvModule: () => void;
- パス解決:
// ビルドディレクトリの取得
getBuildDirectory: (name: string) => string;
// クライアントディレクトリの取得
getClientDirectory: () => string;
// サーバーディレクトリの取得
getServerDirectory: () => string;
// アプリケーションパスの取得
getAppPath: () => string;
- ユーティリティ機能:
// ファイルのコピー
copy: (
from: string,
to: string,
opts?: {
filter?(basename: string): boolean;
replace?: Record<string, string>;
}
) => string[];
// ファイルの圧縮
compress: (directory: string) => Promise<void>;
使用例:
export default {
name: 'my-adapter',
async adapt(builder) {
// ビルドディレクトリのクリーンアップ
const build_directory = builder.getBuildDirectory('my-adapter');
builder.rimraf(build_directory);
builder.mkdirp(build_directory);
// クライアントファイルの書き込み
const client_files = await builder.writeClient(`${build_directory}/client`);
// サーバーファイルの書き込み
const server_files = await builder.writeServer(`${build_directory}/server`);
// 静的ファイルのコピー
builder.copy('static', `${build_directory}/static`);
// 必要に応じてファイルを圧縮
await builder.compress(build_directory);
builder.log.info('アダプテーションが完了しました');
}
};
このインターフェースを使用することで、異なるデプロイ環境に対応するためのカスタムアダプターを効率的に作成できます。
ClientInit
ClientInit
型について解説します。
type ClientInit = () => MaybePromise<void>;
これはSvelteKit 2.10.0以降で利用可能な型定義で、ブラウザでアプリケーションが開始されたときに一度だけ呼び出される初期化関数の型を表します。
特徴:
- 戻り値は
void
またはPromise<void>
が可能(MaybePromise
型) - パラメータは受け取りません
- アプリケーションの起動時に1回のみ実行されます
使用例:
// src/client.ts または同等のファイル
export const init: ClientInit = () => {
// クライアントサイドの初期化処理
console.log('アプリケーションが起動しました');
// 例:アナリティクスの初期化
initializeAnalytics();
// 例:グローバルイベントリスナーの設定
window.addEventListener('error', handleGlobalError);
};
// 非同期処理を含む例
export const init: ClientInit = async () => {
// 必要なリソースの読み込みなど
await loadInitialResources();
// その他の初期化処理
setupApplication();
};
この型は、クライアントサイドでアプリケーションの起動時に必要な初期化処理を定義する際に使用されます。
おわりに
今日は、 SvelteKitのリファレンスについて解説しました。

よっしー
何か質問や相談があれば、コメントをお願いします。また、エンジニア案件の相談にも随時対応していますので、お気軽にお問い合わせください。
それでは、また明日お会いしましょう(^^)
コメント