メインコンテンツへスキップ

設定

プロジェクトの設定は、プロジェクトルートのsvelte.config.jsファイルに記述されています。この設定オブジェクトは、SvelteKitだけでなく、エディタ拡張機能など、Svelteと統合する他のツールでも使用されます。

svelte.config
import const adapter: () => import("@sveltejs/kit").Adapteradapter from '@sveltejs/adapter-auto';

/** @type {import('@sveltejs/kit').Config} */
const const config: Config
@type{import('@sveltejs/kit').Config}
config
= {
Config.kit?: KitConfig | undefined

SvelteKit options

kit
: {
KitConfig.adapter?: Adapter | undefined

Your adapter is run when executing vite build. It determines how the output is converted for different platforms.

@defaultundefined
adapter
: function adapter(): import("@sveltejs/kit").Adapteradapter()
} }; export default const config: Config
@type{import('@sveltejs/kit').Config}
config
;

設定

interface Config {}
compilerOptions?: CompileOptions;
  • デフォルト {}

svelte.compileに渡されるオプション。

extensions?: string[];
  • デフォルト [".svelte"]

Svelteファイルとして扱うファイル拡張子のリスト。

kit?: KitConfig;

SvelteKitオプション

preprocess?: any;

プリプロセッサオプション(もしあれば)。プリプロセッシングは、Viteのプリプロセッサ機能を使用して行うこともできます。

vitePlugin?: PluginOptions;

vite-plugin-svelteプラグインオプション。

[key: string]: any;

Svelteと統合するツールに必要な追加オプション。

KitConfig

kitプロパティはSvelteKitを設定し、以下のプロパティを持つことができます。

adapter

  • デフォルト undefined

vite buildの実行時に実行されるアダプターです。出力の異なるプラットフォームへの変換方法を決定します。

alias

  • デフォルト {}

import文内の値を置き換えるために使用される、ゼロ個以上のエイリアスを含むオブジェクトです。これらのエイリアスは、ViteとTypeScriptに自動的に渡されます。

svelte.config
/** @type {import('@sveltejs/kit').Config} */
const 
const config: {
    kit: {
        alias: {
 'my-file': string;
 'my-directory': string;
            'my-directory/*': string;
        };
    };
}
@type{import('@sveltejs/kit').Config}
config
= {
kit: {
    alias: {
        'my-file': string;
        'my-directory': string;
        'my-directory/*': string;
    };
}
kit
: {
alias: {
    'my-file': string;
    'my-directory': string;
    'my-directory/*': string;
}
alias
: {
// this will match a file 'my-file': 'path/to/my-file.js', // this will match a directory and its contents // (`my-directory/x` resolves to `path/to/my-directory/x`) 'my-directory': 'path/to/my-directory', // an alias ending /* will only match // the contents of a directory, not the directory itself 'my-directory/*': 'path/to/my-directory/*' } } };

組み込みの$libエイリアスは、パッケージングに使用されるため、config.kit.files.libによって制御されます。

npm run devを実行すると、SvelteKitがjsconfig.jsonまたはtsconfig.jsonに必要なエイリアス設定を自動的に生成します。

appDir

  • デフォルト "_app"

SvelteKitが静的アセット(JSやCSSなど)や内部的に使用されるルートを含むものを保持するディレクトリです。

paths.assetsが指定されている場合、${paths.assets}/${appDir}${paths.base}/${appDir}の2つのアプリディレクトリが作成されます。

csp

コンテンツセキュリティポリシーの設定。CSPは、リソースの読み込み元を制限することで、クロスサイトスクリプティング(XSS)攻撃からユーザーを保護するのに役立ちます。例えば、このような設定…

svelte.config
/** @type {import('@sveltejs/kit').Config} */
const 
const config: {
    kit: {
        csp: {
 directives: {
   'script-src': string[];
 };
 reportOnly: {
   'script-src': string[];
   'report-uri': string[];
 };
        };
    };
}
@type{import('@sveltejs/kit').Config}
config
= {
kit: {
    csp: {
        directives: {
 'script-src': string[];
        };
        reportOnly: {
 'script-src': string[];
 'report-uri': string[];
        };
    };
}
kit
: {
csp: {
    directives: {
        'script-src': string[];
    };
    reportOnly: {
        'script-src': string[];
        'report-uri': string[];
    };
}
csp
: {
directives: {
    'script-src': string[];
}
directives
: {
'script-src': ['self'] }, // must be specified with either the `report-uri` or `report-to` directives, or both
reportOnly: {
    'script-src': string[];
    'report-uri': string[];
}
reportOnly
: {
'script-src': ['self'], 'report-uri': ['/'] } } } }; export default
const config: {
    kit: {
        csp: {
 directives: {
   'script-src': string[];
 };
 reportOnly: {
   'script-src': string[];
   'report-uri': string[];
            };
        };
    };
}
@type{import('@sveltejs/kit').Config}
config
;

…は、外部サイトからのスクリプトの読み込みを防ぎます。SvelteKitは、生成するインラインスタイルとスクリプトに対して、指定されたディレクティブにnonceまたはハッシュ(modeに応じて)を追加します。

src/app.htmlに手動で含めたスクリプトとリンクにnonceを追加するには、プレースホルダー%sveltekit.nonce%を使用できます(例:<script nonce="%sveltekit.nonce%">)。

ページがプリレンダリングされると、CSPヘッダーは<meta http-equiv>タグを介して追加されます(この場合、frame-ancestorsreport-urisandboxディレクティブは無視されます)。

mode'auto'の場合、SvelteKitは動的にレンダリングされたページにはnonceを、プリレンダリングされたページにはハッシュを使用します。プリレンダリングされたページでnonceを使用することは安全ではなく、禁止されています。

ほとんどのSvelteトランジションは、インライン<style>要素を作成することによって動作します。アプリでこれらを使用する場合は、style-srcディレクティブを指定しないか、unsafe-inlineを追加する必要があります。

このレベルの設定では不十分で、より動的な要件がある場合は、handleフックを使用して独自のCSPを作成できます。

mode?: 'hash' | 'nonce' | 'auto';

<script>要素と<style>要素を制限するために、ハッシュまたはnonceを使用するかどうか。'auto'は、プリレンダリングされたページにはハッシュを、動的にレンダリングされたページにはnonceを使用します。

directives?: CspDirectives;

Content-Security-Policyヘッダーに追加されるディレクティブ。

reportOnly?: CspDirectives;

Content-Security-Policy-Report-Onlyヘッダーに追加されるディレクティブ。

csrf

クロスサイトリクエストフォージェリ(CSRF)攻撃からの保護。

checkOrigin?: boolean;
  • デフォルト true

POSTPUTPATCH、またはDELETEフォーム送信の受信originヘッダーをチェックし、サーバーのオリジンと一致することを確認するかどうか。

Content-Typeapplication/x-www-form-urlencodedmultipart/form-data、またはtext/plainPOSTPUTPATCH、またはDELETEリクエストを他のオリジンからアプリに送信できるようにするには、このオプションを無効にする必要があります。注意してください!

embedded

  • デフォルト false

アプリがより大きなアプリに埋め込まれているかどうか。trueの場合、SvelteKitはナビゲーションなどに関連するイベントリスナーをwindowではなく%sveltekit.body%の親に追加し、サーバーからparamsを渡します。一般的に、同じページに複数のSvelteKitアプリを埋め込み、それらの中でクライアント側のSvelteKit機能(履歴状態へのプッシュなど)を使用することはサポートされていません。

env

環境変数の設定

dir?: string;
  • デフォルト "."

.envファイルを探すディレクトリ。

publicPrefix?: string;
  • デフォルト "PUBLIC_"

環境変数がクライアント側のコードに公開しても安全であることを示すプレフィックスです。$env/static/public$env/dynamic/publicを参照してください。Viteの環境変数処理を使用している場合、ViteのenvPrefixを別途設定する必要がありますが、一般的にその機能を使用する必要はありません。

privatePrefix?: string;
  • デフォルト ""
  • v1.21.0から利用可能

環境変数をクライアント側のコードに公開しても安全ではないことを示すプレフィックスです。公開プレフィックスとプライベートプレフィックスのどちらにも一致しない環境変数は完全に破棄されます。$env/static/private$env/dynamic/privateを参照してください。

files

プロジェクト内のさまざまなファイルを見つける場所。

assets?: string;
  • デフォルト "static"

安定したURLを持ち、処理されない静的ファイル(favicon.icomanifest.jsonなど)を配置する場所。

hooks?: {}
client?: string;
  • デフォルト "src/hooks.client"

クライアントフックの場所。

server?: string;
  • デフォルト "src/hooks.server"

サーバーフックの場所。

universal?: string;
  • デフォルト "src/hooks"
  • v2.3.0から利用可能

ユニバーサルフックの場所。

lib?: string;
  • デフォルト "src/lib"

アプリの内部ライブラリ。コードベース全体で$libとしてアクセスできます。

params?: string;
  • デフォルト "src/params"

パラメータマッチャーを含むディレクトリ。

routes?: string;
  • デフォルト "src/routes"

アプリの構造を定義するファイル(ルーティングを参照)。

serviceWorker?: string;
  • デフォルト "src/service-worker"

サービスワーカーのエントリポイントの場所(サービスワーカーを参照)。

appTemplate?: string;
  • デフォルト "src/app.html"

HTMLレスポンスのテンプレートの場所。

errorTemplate?: string;
  • デフォルト "src/error.html"

フォールバックエラーレスポンスのテンプレートの場所。

inlineStyleThreshold

  • デフォルト 0

HTMLの先頭にある<style>ブロック内のインラインCSS。このオプションは、インライン化するCSSファイルの最大長(UTF-16コード単位、String.lengthプロパティで指定)を数値で指定します。この値より小さいページに必要なすべてのCSSファイルは、マージされ、<style>ブロックにインラインされます。

これにより、初期リクエストが減り、First Contentful Paintスコアが向上する可能性があります。ただし、HTML出力が大きくなり、ブラウザキャッシュの有効性が低下します。注意して使用してください。

moduleExtensions

  • デフォルト [".js", ".ts"]

SvelteKitがモジュールとして扱うファイル拡張子の配列です。config.extensionsconfig.kit.moduleExtensionsのどちらにも一致しない拡張子のファイルは、ルーターによって無視されます。

outDir

  • デフォルト ".svelte-kit"

devbuild中にSvelteKitがファイル書き込むディレクトリです。このディレクトリはバージョン管理から除外する必要があります。

output

ビルド出力形式に関するオプション

preloadStrategy?: 'modulepreload' | 'preload-js' | 'preload-mjs';
  • デフォルト "modulepreload"
  • v1.8.4から利用可能

SvelteKitは、インポートのウォーターフォールを防ぐために、最初のページに必要なJavaScriptモジュールをプリロードします。これにより、アプリケーションの起動が高速化されます。トレードオフの異なる3つの戦略があります。

  • modulepreload - <link rel="modulepreload">を使用します。Chromiumベースのブラウザ、Firefox 115+、Safari 17+で最高の結果を提供します。古いブラウザでは無視されます。
  • preload-js - <link rel="preload">を使用します。ChromiumとSafariでウォーターフォールを防ぎますが、Chromiumは各モジュールを2回(スクリプトとして1回、モジュールとして1回)解析します。Firefoxではモジュールが2回要求される原因になります。これは、Chromiumユーザーのわずかなパフォーマンス低下を犠牲にして、iOSデバイスのユーザーのパフォーマンスを最大限に高めたい場合に適した設定です。
  • preload-mjs - <link rel="preload"> を使用しますが、拡張子を .mjs とすることで、Chromium での二重解析を防ぎます。一部の静的ウェブサーバーは、Content-Type: application/javascript ヘッダー付きで .mjs ファイルを提供できないため、アプリケーションが動作しなくなる場合があります。それが当てはまらない場合は、modulepreload がより広くサポートされるまでは、最も多くのユーザーにとって最高の性能を発揮するオプションです。

paths

assets?: '' | `http://${string}` | `https://${string}`;
  • デフォルト ""

アプリケーションのファイルが提供される絶対パス。ファイルが何らかのストレージバケットから提供される場合に便利です。

base?: '' | `/${string}`;
  • デフォルト ""

ルート相対パスで、/ で始まり(ただし、空文字列でない限り、/ で終わることはありません。例:/base-path)。アプリケーションが提供される場所を指定し、アプリケーションをルート以外のパスに配置できるようにします。ルート相対リンクの先頭にベース値を付ける必要があることに注意してください。付けないと、ドメインのルートではなく、base を指すことになります(ブラウザの動作です)。これには、$app/paths からの base を使用できます:<a href="{base}/your-page">Link</a>。これを頻繁に記述する場合は、再利用可能なコンポーネントに抽出することを検討してください。

relative?: boolean;
  • デフォルト true
  • v1.9.0から利用可能

相対アセットパスを使用するかどうか。

trueの場合、$app/pathsからインポートされたbaseassetsは、サーバーサイドレンダリング中に相対アセットパスに置き換えられ、より移植性の高いHTMLになります。falseの場合、%sveltekit.assets%とビルドアーティファクトへの参照は、paths.assetsが外部URLでない限り、常にルート相対パスになります。

シングルページアプリケーション のフォールバックページは、この設定に関係なく、常に絶対パスを使用します。

アプリケーションで<base>要素を使用する場合は、これをfalseに設定してください。そうしないと、アセットURLが現在のページではなく<base> URLに対して誤って解決されます。

1.0では、undefinedが有効な値であり、デフォルトで設定されていました。その場合、paths.assetsが外部でない場合、SvelteKitは%sveltekit.assets%を相対パスに置き換え、ビルドアーティファクトへの参照に相対パスを使用しますが、$app/pathsからインポートされたbaseassetsは、設定で指定されたとおりになります。

prerender

プリレンダリング を参照してください。

concurrency?: number;
  • デフォルト 1

同時にプリレンダリングできるページ数。JSはシングルスレッドですが、プリレンダリングのパフォーマンスがネットワークに依存する場合(たとえば、リモートCMSからコンテンツを読み込む場合)、ネットワーク応答を待っている間に他のタスクを処理することで、速度を上げることができます。

crawl?: boolean;
  • デフォルト true

SvelteKitがentriesからのリンクをたどって、プリレンダリングするページを検索するかどうか。

entries?: var Array: ArrayConstructorArray<'*' | `/${string}`>;
  • デフォルト ["*"]

プリレンダリングするページ、またはクロールを開始するページの配列(crawl: trueの場合)。*文字列には、必須の[パラメーター]を含まないすべてのルートが含まれ、オプションのパラメーターは空として含まれます(SvelteKitはパラメーターがどのような値を持つべきかを知らないため)。

handleHttpError?: PrerenderHttpErrorHandlerValue;
  • デフォルト "fail"
  • v1.15.7から利用可能

アプリケーションのプリレンダリング中に発生したHTTPエラーへの対応方法。

  • 'fail' — ビルドを失敗させる
  • 'ignore' - エラーを無視して続行する
  • 'warn' — 続行するが、警告を表示する
  • (details) => voidstatuspathreferrerreferenceTypemessageプロパティを持つdetailsオブジェクトを受け取るカスタムエラーハンドラー。この関数からthrowすると、ビルドは失敗します。
svelte.config
/** @type {import('@sveltejs/kit').Config} */
const 
const config: {
    kit: {
        prerender: {
 handleHttpError: ({ path, referrer, message }: {
   path: any;
   referrer: any;
     message: any;
 }) => void;
        };
    };
}
@type{import('@sveltejs/kit').Config}
config
= {
kit: {
    prerender: {
        handleHttpError: ({ path, referrer, message }: {
 path: any;
 referrer: any;
 message: any;
        }) => void;
    };
}
kit
: {
prerender: {
    handleHttpError: ({ path, referrer, message }: {
        path: any;
        referrer: any;
        message: any;
    }) => void;
}
prerender
: {
handleHttpError: ({ path, referrer, message }: {
    path: any;
    referrer: any;
    message: any;
}) => void
handleHttpError
: ({ path: anypath, referrer: anyreferrer, message: anymessage }) => {
// ignore deliberate link to shiny 404 page if (path: anypath === '/not-found' && referrer: anyreferrer === '/blog/how-we-built-our-404-page') { return; } // otherwise fail the build throw new
var Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+1 overload)
Error
(message: anymessage);
} } } };
handleMissingId?: PrerenderMissingIdHandlerValue;
  • デフォルト "fail"
  • v1.15.7から利用可能

プリレンダリングされたページ間のハッシュリンクが、宛先ページのidと一致しない場合の対応方法。

  • 'fail' — ビルドを失敗させる
  • 'ignore' - エラーを無視して続行する
  • 'warn' — 続行するが、警告を表示する
  • (details) => voidpathidreferrersmessageプロパティを持つdetailsオブジェクトを受け取るカスタムエラーハンドラー。この関数からthrowすると、ビルドは失敗します。
handleEntryGeneratorMismatch?: PrerenderEntryGeneratorMismatchHandlerValue;
  • デフォルト "fail"
  • v1.16.0から利用可能

entriesエクスポートによって生成されたエントリが、それが生成されたルートと一致しない場合の対応方法。

  • 'fail' — ビルドを失敗させる
  • 'ignore' - エラーを無視して続行する
  • 'warn' — 続行するが、警告を表示する
  • (details) => voidgeneratedFromIdentrymatchedIdmessageプロパティを持つdetailsオブジェクトを受け取るカスタムエラーハンドラー。この関数からthrowすると、ビルドは失敗します。
var origin: stringorigin?: string;
  • デフォルト "http://sveltekit-prerender"

プリレンダリング中のurl.originの値。レンダリングされたコンテンツに含まれる場合に便利です。

serviceWorker

register?: boolean;
  • デフォルト true

サービスワーカーが存在する場合、自動的に登録するかどうか。

files?(filepath: stringfilepath: string): boolean;
  • デフォルト (filename) => !/\.DS_Store/.test(filename)

staticディレクトリのどのファイルが$service-worker.filesで使用可能になるかを決定します。

typescript

config?: (config: Record<string, any>config: type Record<K extends keyof any, T> = { [P in K]: T; }

Construct a type with a set of properties K of type T

Record
<string, any>) => Record<string, any> | void;
  • デフォルト (config) => config
  • v1.3.0から利用可能

生成されたtsconfig.jsonを編集できる関数。設定を変更(推奨)するか、新しい設定を返すことができます。これは、たとえば、モノレポのルートにある共有tsconfig.jsonを拡張する場合に便利です。

version

ユーザーがアプリケーションを使用している間に新しいバージョンのアプリケーションをデプロイすると、クライアント側のナビゲーションがバグを起こす可能性があります。新しいページのコードが既にロードされている場合、古いコンテンツが含まれている可能性があります。ロードされていない場合、アプリケーションのルートマニフェストは、もはや存在しないJavaScriptファイルを指している可能性があります。SvelteKitは、バージョン管理を通じてこの問題の解決に役立ちます。SvelteKitがページの読み込み中にエラーが発生し、新しいバージョンがデプロイされていることを検出すると(ここで指定されたnameを使用し、デフォルトではビルドのタイムスタンプになります)、従来のフルページナビゲーションにフォールバックします。ただし、すべてのナビゲーションがエラーになるわけではありません。たとえば、次のページのJavaScriptが既にロードされている場合などです。これらの場合でもフルページナビゲーションを強制する場合は、pollIntervalを設定し、beforeNavigateを使用するなどの手法を使用します。

+layout
<script>
	import { beforeNavigate } from '$app/navigation';
	import { updated } from '$app/stores';

	beforeNavigate(({ willUnload, to }) => {
		if ($updated && !willUnload && to?.url) {
			location.href = to.url.href;
		}
	});
</script>

pollIntervalをゼロ以外の値に設定すると、SvelteKitはバックグラウンドで新しいバージョンのポーリングを行い、新しいバージョンを検出すると、updatedストアの値をtrueに設定します。

const name: void
@deprecated
name
?: string;

現在のアプリケーションのバージョンの文字列。指定する場合は、決定論的である必要があります(例:Math.random()またはDate.now().toString()ではなく、コミット参照)。そうでない場合は、ビルドのタイムスタンプがデフォルトになります。

たとえば、現在のコミットハッシュを使用するには、git rev-parse HEADを使用できます。

svelte.config
import * as module "node:child_process"child_process from 'node:child_process';

export default {
	
kit: {
    version: {
        name: string;
    };
}
kit
: {
version: {
    name: string;
}
version
: {
name: stringname: module "node:child_process"child_process.function execSync(command: string): Buffer (+3 overloads)

The child_process.execSync() method is generally identical to {@link exec } with the exception that the method will not return until the child process has fully closed. When a timeout has been encountered and killSignal is sent, the method won’t return until the process has completely exited. If the child process intercepts and handles the SIGTERM signal and doesn’t exit, the parent process will wait until the child process has exited.

If the process times out or has a non-zero exit code, this method will throw. The Error object will contain the entire result from {@link spawnSync } .

Never pass unsanitized user input to this function. Any input containing shell metacharacters may be used to trigger arbitrary command execution.

@sincev0.11.12
@paramcommand The command to run.
@returnThe stdout from the command.
execSync
('git rev-parse HEAD').Buffer.toString(encoding?: BufferEncoding, start?: number, end?: number): string

Decodes buf to a string according to the specified character encoding inencoding. start and end may be passed to decode only a subset of buf.

If encoding is 'utf8' and a byte sequence in the input is not valid UTF-8, then each invalid byte is replaced with the replacement character U+FFFD.

The maximum length of a string instance (in UTF-16 code units) is available as {@link constants.MAX_STRING_LENGTH } .

import { Buffer } from 'node:buffer';

const buf1 = Buffer.allocUnsafe(26);

for (let i = 0; i &#x3C; 26; i++) {
  // 97 is the decimal ASCII value for 'a'.
  buf1[i] = i + 97;
}

console.log(buf1.toString('utf8'));
// Prints: abcdefghijklmnopqrstuvwxyz
console.log(buf1.toString('utf8', 0, 5));
// Prints: abcde

const buf2 = Buffer.from('tést');

console.log(buf2.toString('hex'));
// Prints: 74c3a97374
console.log(buf2.toString('utf8', 0, 3));
// Prints: té
console.log(buf2.toString(undefined, 0, 3));
// Prints: té
@sincev0.1.90
@paramencoding The character encoding to use.
@paramstart The byte offset to start decoding at.
@paramend The byte offset to stop decoding at (not inclusive).
toString
().String.trim(): string

Removes the leading and trailing white space and line terminator characters from a string.

trim
()
} } };
pollInterval?: number;
  • デフォルト 0

バージョン変更をポーリングする間隔(ミリ秒単位)。これが0の場合、ポーリングは行われません。

GitHubでこのページを編集する