よくある質問
その他のリソース
Svelte FAQ および vite-plugin-svelte
FAQも、これらのライブラリに由来する質問の回答として参照してください。
SvelteKitで何が作れますか?
SvelteKitは、ほとんどの種類のアプリケーションを作成するために使用できます。SvelteKitは、すぐに使用できる多くの機能をサポートしています。
- load 関数と APIルートによる動的なページコンテンツ。
- サーバーサイドレンダリング(SSR)によるSEOフレンドリーな動的コンテンツ。
- SSRとフォームアクションによる、ユーザーフレンドリーなプログレッシブエンハンスされたインタラクティブページ。
- プリレンダリングによる静的ページ。
SvelteKitは、アダプターを介して、幅広いホストアーキテクチャにもデプロイできます。SSRが使用されている場合(またはプリレンダリングなしでサーバーサイドロジックが追加されている場合)、これらの関数はターゲットバックエンドに適合されます。いくつかの例を以下に示します。
- Node.jsバックエンドを使用した、自己ホスト型の動的Webアプリケーション。
- リモート関数としてデプロイされたバックエンドローダーおよびAPIを備えた、サーバーレスWebアプリケーション。人気のデプロイオプションについては、ゼロコンフィグデプロイを参照してください。
- ブログやCDNまたは静的ホストでホストされている複数ページのサイトなどの静的にプリレンダリングされたサイト。静的に生成されたサイトは、バックエンドなしで出荷されます。
- API駆動の動的コンテンツ用のクライアントサイドルーティングとレンダリングを備えた、シングルページアプリケーション(SPA)。SPAはバックエンドなしで出荷され、サーバーレンダリングされません。このオプションは、SvelteKitをPHP、.Net、Java、C、Golang、Rustなどで記述されたアプリとバンドルする場合によく選択されます。
- 上記の組み合わせ。一部のルートは静的であり、一部のルートはバックエンド関数を使用して動的情報をフェッチできます。これは、SSRをオプトアウトするオプションを含むページオプションで構成できます。
SSRをサポートするには、Node.jsまたはDenoベースのサーバー、サーバーレス関数、エッジ関数などのJSバックエンドが必要です。
また、カスタムアダプターを作成したり、コミュニティアダプターを利用して、SvelteKitを特殊なサーバー環境、ブラウザー拡張機能、またはネイティブアプリケーションなどのより多くのプラットフォームにデプロイすることもできます。詳細および統合については、連携を参照してください。
package.jsonの詳細をアプリケーションに含めるにはどうすればよいですか?
SvelteKitはsvelte.config.js
がESモジュールであると想定しているため、JSONファイルを直接requireすることはできません。アプリケーションのバージョン番号やpackage.json
のその他の情報をアプリケーションに含める場合は、次のようにJSONをロードできます。
import { function readFileSync(path: PathOrFileDescriptor, options?: {
encoding?: null | undefined;
flag?: string | undefined;
} | null): Buffer (+2 overloads)
Returns the contents of the path
.
For detailed information, see the documentation of the asynchronous version of
this API:
{@link
readFile
}
.
If the encoding
option is specified then this function returns a
string. Otherwise it returns a buffer.
Similar to
{@link
readFile
}
, when the path is a directory, the behavior of fs.readFileSync()
is platform-specific.
import { readFileSync } from 'node:fs';
// macOS, Linux, and Windows
readFileSync('<directory>');
// => [Error: EISDIR: illegal operation on a directory, read <directory>]
// FreeBSD
readFileSync('<directory>'); // => <data>
readFileSync } from 'node:fs';
import { function fileURLToPath(url: string | URL, options?: FileUrlToPathOptions): string
This function ensures the correct decodings of percent-encoded characters as
well as ensuring a cross-platform valid absolute path string.
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
new URL('file:///C:/path/').pathname; // Incorrect: /C:/path/
fileURLToPath('file:///C:/path/');// Correct: C:\path\ (Windows)
new URL('file://nas/foo.txt').pathname; // Incorrect: /foo.txt
fileURLToPath('file://nas/foo.txt'); // Correct: \\nas\foo.txt (Windows)
new URL('file:///你好.txt').pathname; // Incorrect: /%E4%BD%A0%E5%A5%BD.txt
fileURLToPath('file:///你好.txt');// Correct: /你好.txt (POSIX)
new URL('file:///hello world').pathname; // Incorrect: /hello%20world
fileURLToPath('file:///hello world'); // Correct: /hello world (POSIX)
fileURLToPath } from 'node:url';
const const path: string
path = function fileURLToPath(url: string | URL, options?: FileUrlToPathOptions): string
This function ensures the correct decodings of percent-encoded characters as
well as ensuring a cross-platform valid absolute path string.
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
new URL('file:///C:/path/').pathname; // Incorrect: /C:/path/
fileURLToPath('file:///C:/path/');// Correct: C:\path\ (Windows)
new URL('file://nas/foo.txt').pathname; // Incorrect: /foo.txt
fileURLToPath('file://nas/foo.txt'); // Correct: \\nas\foo.txt (Windows)
new URL('file:///你好.txt').pathname; // Incorrect: /%E4%BD%A0%E5%A5%BD.txt
fileURLToPath('file:///你好.txt');// Correct: /你好.txt (POSIX)
new URL('file:///hello world').pathname; // Incorrect: /hello%20world
fileURLToPath('file:///hello world'); // Correct: /hello world (POSIX)
fileURLToPath(new new URL(input: string | {
toString: () => string;
}, base?: string | URL): URL
Browser-compatible URL
class, implemented by following the WHATWG URL
Standard. Examples of parsed URLs may be found in the Standard itself.
The URL
class is also available on the global object.
In accordance with browser conventions, all properties of URL
objects
are implemented as getters and setters on the class prototype, rather than as
data properties on the object itself. Thus, unlike legacy urlObject
s,
using the delete
keyword on any properties of URL
objects (e.g. delete myURL.protocol
, delete myURL.pathname
, etc) has no effect but will still
return true
.
URL('package.json', import.meta.ImportMeta.url: string
The absolute file:
URL of the module.
url));
const const pkg: any
pkg = var JSON: JSON
An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.
JSON.JSON.parse(text: string, reviver?: (this: any, key: string, value: any) => any): any
Converts a JavaScript Object Notation (JSON) string into an object.
parse(function readFileSync(path: PathOrFileDescriptor, options: {
encoding: BufferEncoding;
flag?: string | undefined;
} | BufferEncoding): string (+2 overloads)
Synchronously reads the entire contents of a file.
readFileSync(const path: string
path, 'utf8'));
パッケージを含めようとするとエラーが発生しますが、どうすれば修正できますか?
ライブラリのインクルードに関連するほとんどの問題は、パッケージングが正しくないことが原因です。ライブラリのパッケージングがNode.jsと互換性があるかどうかは、publint Webサイトに入力することで確認できます。
ライブラリが正しくパッケージ化されているかどうかを確認する際に、注意すべき点がいくつかあります。
exports
は、main
やmodule
などの他のエントリポイントフィールドよりも優先されます。exports
フィールドを追加すると、ディープインポートが妨げられるため、下位互換性がない可能性があります。- ESMファイルは、
"type": "module"
が設定されていない限り.mjs
で終わる必要があり、設定されている場合は、CommonJSファイルは.cjs
で終わる必要があります。 exports
がない場合はmain
を定義する必要があります。CommonJSまたはESMファイルのいずれかで、前の箇条書きに従う必要があります。module
フィールドが定義されている場合は、ESMファイルを参照する必要があります。- Svelteコンポーネントは、コンパイルされていない
.svelte
ファイルとして配布する必要があり、パッケージ内のJSはESMとしてのみ記述する必要があります。TypeScriptやSCSSなどのカスタムスクリプトおよびスタイル言語は、プレーンなJSとCSSとしてそれぞれプリプロセスする必要があります。この処理を行うSvelteライブラリのパッケージングには、svelte-package
を使用することをお勧めします。
ライブラリは、特にSvelteコンポーネントライブラリの依存関係である場合、ESMバージョンを配布するとViteを使用したブラウザーで最適に動作します。ライブラリの作成者にESMバージョンを提供することを提案することを検討できます。ただし、CommonJS(CJS)の依存関係も、デフォルトでは、vite-plugin-svelte
がesbuild
を使用してそれらをESMに変換するためにViteに事前にバンドルするように要求するため、機能します。
それでも問題が発生する場合は、Viteの問題トラッカーと、問題のライブラリの問題トラッカーの両方を検索することをお勧めします。問題は、optimizeDeps
またはssr
設定値を調整することで回避できる場合がありますが、これは一時的な回避策としてのみ使用し、問題のライブラリを修正することをお勧めします。
SvelteKitでビュー遷移APIを使用するにはどうすればよいですか?
SvelteKitにはビュー遷移との特定の統合はありませんが、onNavigate
でdocument.startViewTransition
を呼び出して、すべてのクライアント側のナビゲーションでビュー遷移をトリガーできます。
import { function onNavigate(callback: (navigation: import("@sveltejs/kit").OnNavigate) => MaybePromise<void | (() => void)>): void
A lifecycle function that runs the supplied callback
immediately before we navigate to a new URL except during full-page navigations.
If you return a Promise
, SvelteKit will wait for it to resolve before completing the navigation. This allows you to — for example — use document.startViewTransition
. Avoid promises that are slow to resolve, since navigation will appear stalled to the user.
If a function (or a Promise
that resolves to a function) is returned from the callback, it will be called once the DOM has updated.
onNavigate
must be called during a component initialization. It remains active as long as the component is mounted.
onNavigate } from '$app/navigation';
function onNavigate(callback: (navigation: import("@sveltejs/kit").OnNavigate) => MaybePromise<void | (() => void)>): void
A lifecycle function that runs the supplied callback
immediately before we navigate to a new URL except during full-page navigations.
If you return a Promise
, SvelteKit will wait for it to resolve before completing the navigation. This allows you to — for example — use document.startViewTransition
. Avoid promises that are slow to resolve, since navigation will appear stalled to the user.
If a function (or a Promise
that resolves to a function) is returned from the callback, it will be called once the DOM has updated.
onNavigate
must be called during a component initialization. It remains active as long as the component is mounted.
onNavigate((navigation: OnNavigate
navigation) => {
if (!var document: Document
document.startViewTransition) return;
return new var Promise: PromiseConstructor
new <void | (() => void)>(executor: (resolve: (value: void | (() => void) | PromiseLike<void | (() => void)>) => void, reject: (reason?: any) => void) => void) => Promise<void | (() => void)>
Creates a new Promise.
Promise((resolve: (value: void | (() => void) | PromiseLike<void | (() => void)>) => void
resolve) => {
var document: Document
document.startViewTransition(async () => {
resolve: (value: void | (() => void) | PromiseLike<void | (() => void)>) => void
resolve();
await navigation: OnNavigate
navigation.Navigation.complete: Promise<void>
A promise that resolves once the navigation is complete, and rejects if the navigation
fails or is aborted. In the case of a willUnload
navigation, the promise will never resolve
complete;
});
});
});
詳細については、Svelteブログの「ビュー遷移のアンロック」を参照してください。
SvelteKitでXを使用するにはどうすればよいですか?
連携に関するドキュメントセクションを必ずお読みください。それでも問題が発生する場合は、一般的な問題の解決策を以下に示します。
データベースを設定するにはどうすればよいですか?
サーバールートにデータベースをクエリするコードを配置します。 .svelteファイルでデータベースをクエリしないでください。すぐに接続を確立し、アプリ全体でクライアントをシングルトンとしてアクセス可能にするdb.js
または同様のファイルを作成できます。hooks.server.js
で1回限りのセットアップコードを実行し、データベースヘルパーを必要なエンドポイントにインポートできます。
documentまたはwindowに依存するクライアント側専用のライブラリを使用するにはどうすればよいですか?
document
またはwindow
変数へのアクセスが必要な場合、またはクライアント側でのみ実行する必要があるコードがある場合は、browser
チェックでラップできます。
import { const browser: boolean
true
if the app is running in the browser.
browser } from '$app/environment';
if (const browser: boolean
true
if the app is running in the browser.
browser) {
// client-only code here
}
コンポーネントが最初にDOMにレンダリングされた後に実行する場合は、onMount
でコードを実行することもできます。
import { function onMount<T>(fn: () => NotFunction<T> | Promise<NotFunction<T>> | (() => any)): void
The onMount
function schedules a callback to run as soon as the component has been mounted to the DOM.
It must be called during the component’s initialisation (but doesn’t need to live inside the component;
it can be called from an external module).
If a function is returned synchronously from onMount
, it will be called when the component is unmounted.
onMount
does not run inside server-side components.
onMount } from 'svelte';
onMount<void>(fn: () => void | (() => any) | Promise<void>): void
The onMount
function schedules a callback to run as soon as the component has been mounted to the DOM.
It must be called during the component’s initialisation (but doesn’t need to live inside the component;
it can be called from an external module).
If a function is returned synchronously from onMount
, it will be called when the component is unmounted.
onMount
does not run inside server-side components.
onMount(async () => {
const { const method: any
method } = await import('some-browser-only-library');
const method: any
method('hello world');
});
使用したいライブラリが副作用のないものである場合は、静的にインポートすることもでき、サーバー側のビルドでツリーシェイクされ、onMount
は自動的にno-opに置き換えられます。
import { function onMount<T>(fn: () => NotFunction<T> | Promise<NotFunction<T>> | (() => any)): void
The onMount
function schedules a callback to run as soon as the component has been mounted to the DOM.
It must be called during the component’s initialisation (but doesn’t need to live inside the component;
it can be called from an external module).
If a function is returned synchronously from onMount
, it will be called when the component is unmounted.
onMount
does not run inside server-side components.
onMount } from 'svelte';
import { module "some-browser-only-library"
method } from 'some-browser-only-library';
onMount<void>(fn: () => void | (() => any) | Promise<void>): void
The onMount
function schedules a callback to run as soon as the component has been mounted to the DOM.
It must be called during the component’s initialisation (but doesn’t need to live inside the component;
it can be called from an external module).
If a function is returned synchronously from onMount
, it will be called when the component is unmounted.
onMount
does not run inside server-side components.
onMount(() => {
module "some-browser-only-library"
method('hello world');
});
最後に、{#await}
ブロックの使用も検討できます。
<script>
import { browser } from '$app/environment';
const ComponentConstructor = browser ?
import('some-browser-only-library').then((module) => module.Component) :
new Promise(() => {});
</script>
{#await ComponentConstructor}
<p>Loading...</p>
{:then component}
<svelte:component this={component} />
{:catch error}
<p>Something went wrong: {error.message}</p>
{/await}
異なるバックエンドAPIサーバーを使用するにはどうすればよいですか?
event.fetch
を使用して外部APIサーバーからデータをリクエストできますが、CORSに対処する必要があることに注意してください。これにより、一般的にリクエストをプリフライトする必要があるため、レイテンシーが高くなるなどの複雑さが生じます。別のサブドメインへのリクエストも、追加のDNSルックアップ、TLSセットアップなどによりレイテンシーが増加する可能性があります。この方法を使用する場合は、handleFetch
が役立つ場合があります。
別の方法として、CORSの頭痛の種を回避するためにプロキシを設定する方法があります。本番環境では、/api
のようなパスをAPIサーバーに書き換えます。ローカル開発では、Viteのserver.proxy
オプションを使用します。
本番環境でのリライトの設定方法は、デプロイプラットフォームによって異なります。リライトがオプションでない場合は、代わりにAPIルートを追加できます。
/** @type {import('./$types').RequestHandler} */
export function function GET({ params, url }: {
params: any;
url: any;
}): Promise<Response>
GET({ params: any
params, url: any
url }) {
return function fetch(input: string | URL | globalThis.Request, init?: RequestInit): Promise<Response> (+1 overload)
fetch(`https://my-api-server.com/${params: any
params.path + url: any
url.search}`);
}
import type { type RequestHandler = (event: Kit.RequestEvent<Record<string, any>, string | null>) => MaybePromise<Response>
type RequestHandler = (event: Kit.RequestEvent<Record<string, any>, string | null>) => MaybePromise<Response>
RequestHandler } from './$types';
export const const GET: RequestHandler
GET: type RequestHandler = (event: Kit.RequestEvent<Record<string, any>, string | null>) => MaybePromise<Response>
type RequestHandler = (event: Kit.RequestEvent<Record<string, any>, string | null>) => MaybePromise<Response>
RequestHandler = ({ params: Record<string, any>
The parameters of the current route - e.g. for a route like /blog/[slug]
, a { slug: string }
object
params, url: URL
The requested URL.
url }) => {
return function fetch(input: string | URL | globalThis.Request, init?: RequestInit): Promise<Response> (+1 overload)
fetch(`https://my-api-server.com/${params: Record<string, any>
The parameters of the current route - e.g. for a route like /blog/[slug]
, a { slug: string }
object
params.path + url: URL
The requested URL.
url.URL.search: string
search}`);
};
(必要に応じて、POST
/ PATCH
などのリクエストをプロキシし、request.headers
を転送する必要がある場合があることに注意してください。)
ミドルウェアを使用するにはどうすればよいですか?
adapter-node
は、本番モード用に独自のサーバーで使用できるミドルウェアを構築します。開発では、Viteプラグインを使用してミドルウェアをViteに追加できます。例:
import { module "@sveltejs/kit/vite"
sveltekit } from '@sveltejs/kit/vite';
/** @type {import('vite').Plugin} */
const const myPlugin: Plugin<any>
myPlugin = {
OutputPlugin.name: string
name: 'log-request-middleware',
Plugin<any>.configureServer?: ObjectHook<ServerHook> | undefined
Configure the vite server. The hook receives the
{@link
ViteDevServer
}
instance. This can also be used to store a reference to the server
for use in other hooks.
The hooks will be called before internal middlewares are applied. A hook
can return a post hook that will be called after internal middlewares
are applied. Hook can be async functions and will be called in series.
configureServer(server: ViteDevServer
server) {
server: ViteDevServer
server.ViteDevServer.middlewares: Connect.Server
A connect app instance.
- Can be used to attach custom middlewares to the dev server.
- Can also be used as the handler function of a custom http server
or as a middleware in any connect-style Node.js frameworks
middlewares.Connect.Server.use(fn: Connect.NextHandleFunction): Connect.Server (+3 overloads)
Utilize the given middleware handle
to the given route
,
defaulting to /. This “route” is the mount-point for the
middleware, when given a value other than / the middleware
is only effective when that segment is present in the request’s
pathname.
For example if we were to mount a function at /admin, it would
be invoked on /admin, and /admin/settings, however it would
not be invoked for /, or /posts.
use((req: Connect.IncomingMessage
req, res: ServerResponse<IncomingMessage>
res, next: Connect.NextFunction
next) => {
var console: Console
The console
module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
- A
Console
class with methods such as console.log()
, console.error()
and console.warn()
that can be used to write to any Node.js stream.
- A global
console
instance configured to write to process.stdout
and
process.stderr
. The global console
can be used without calling require('console')
.
Warning: The global console object’s methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the note on process I/O
for
more information.
Example using the global console
:
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console
class:
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
console.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to stdout
with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to printf(3)
(the arguments are all passed to util.format()
).
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
See util.format()
for more information.
log(`Got request ${req: Connect.IncomingMessage
req.IncomingMessage.url?: string | undefined
Only valid for request obtained from
{@link
Server
}
.
Request URL string. This contains only the URL that is present in the actual
HTTP request. Take the following request:
GET /status?name=ryan HTTP/1.1
Accept: text/plain
To parse the URL into its parts:
new URL(`http://${process.env.HOST ?? 'localhost'}${request.url}`);
When request.url
is '/status?name=ryan'
and process.env.HOST
is undefined:
$ node
> new URL(`http://${process.env.HOST ?? 'localhost'}${request.url}`);
URL {
href: 'http://localhost/status?name=ryan',
origin: 'http://localhost',
protocol: 'http:',
username: '',
password: '',
host: 'localhost',
hostname: 'localhost',
port: '',
pathname: '/status',
search: '?name=ryan',
searchParams: URLSearchParams { 'name' => 'ryan' },
hash: ''
}
Ensure that you set process.env.HOST
to the server’s host name, or consider replacing this part entirely. If using req.headers.host
, ensure proper
validation is used, as clients may specify a custom Host
header.
url}`);
next: (err?: any) => void
next();
});
}
};
/** @type {import('vite').UserConfig} */
const const config: UserConfig
config = {
UserConfig.plugins?: PluginOption[] | undefined
Array of vite plugins to use.
plugins: [const myPlugin: Plugin<any>
myPlugin, module "@sveltejs/kit/vite"
sveltekit()]
};
export default const config: UserConfig
config;
順序の制御方法など、詳細については、ViteのconfigureServer
ドキュメントを参照してください。
Yarn 2で動作しますか?
ある程度動作します。Plug'n'Play機能(別名「pnp」)は壊れています(Nodeモジュール解決アルゴリズムから逸脱し、SvelteKitで使用するネイティブJavaScriptモジュール(および、パッケージ数の増加)ではまだ機能しません)。.yarnrc.yml
ファイルでnodeLinker: 'node-modules'
を使用してpnpを無効にできますが、npmまたはpnpmを使用する方がおそらく簡単です。これは同様に高速で効率的ですが、互換性の問題はありません。
Yarn 3 はどのように使えばいいですか?
現在、最新の Yarn (バージョン 3) における ESM サポートは 実験的 とみなされています。
以下は動作するように見えますが、結果は異なる場合があります。
まず、新しいアプリケーションを作成します。
yarn create svelte myapp
cd myapp
次に、Yarn Berry を有効にします。
yarn set version berry
yarn install
Yarn 3 のグローバルキャッシュ
Yarn Berry のより興味深い機能の1つは、ディスク上のプロジェクトごとに複数のコピーを持つ代わりに、パッケージに対して単一のグローバルキャッシュを持つ機能です。しかし、enableGlobalCache
を true に設定するとビルドが失敗するため、次の内容を .yarnrc.yml
ファイルに追加することをお勧めします。
nodeLinker: node-modules
これにより、パッケージはローカルの node_modules ディレクトリにダウンロードされますが、上記の問題は回避され、現時点では Yarn のバージョン3を使用するための最善の方法です。