Skip to content

非公式本サイトは非公式の日本語ドキュメントであり、Cloudflare 公式サイトではありません。最新情報はdevelopers.cloudflare.comをご確認ください。

モジュールサポート

最終更新 Markdown で表示Agent セットアップ

Pages Functions は、Workers と同様に、いくつかのモジュール種別をサポートします。Functions のコード内で、WebAssembly (Wasm)、textbinary ファイルなどの外部モジュールをインポートして使えます。

このガイドでは、Pages Functions 内でこれらのモジュール種別を使う方法を説明します。

ECMAScript Modules

ECMAScript modules(略して ES Modules)は、JavaScript の公式な 標準 モジュールシステムです。モジュール化して再利用できる JavaScript を書くうえでの推奨手段です。

ES Modulesimportexport 文で定義します。次は ES Modules 形式で書いたスクリプトと、そのモジュールをインポートする Pages Function の例です。

export function greeting(name: string): string {
  return `Hello ${name}!`;
}
import { greeting } from "../src/greeting.ts";

export async function onRequest(context) {
	return new Response(`${greeting("Pages Functions")}`);
}

WebAssembly Modules

WebAssembly(略称 Wasm)を使うと、Rust、Go、C などの言語をバイナリ形式にコンパイルし、Web ブラウザー、Cloudflare Workers、Cloudflare Pages Functions、その他の WebAssembly ランタイムなど、幅広い環境で実行できます。

WebAssembly で配布、読み込み、実行できるコードの単位を モジュール と呼びます。

Pages Functions のコード内で Wasm Modules をインポートする基本的な例です。

import addModule from "add.wasm";

export async function onRequest() {
	const addInstance = await WebAssembly.instantiate(addModule);
	return new Response(
		`The meaning of life is ${addInstance.exports.add(20, 1)}`,
	);
}

Text Modules

Text Modules は、HTML ファイルなどのリソースを String としてインポートする、非標準の仕組みです。

次の HTML ファイルを Pages Functions のコードへインポートするには:

<!DOCTYPE html>
<html>
	<body>
		<h1>Hello Pages Functions!</h1>
	</body>
</html>

次のスクリプトを使います。

import html from "../index.html";

export async function onRequest() {
	return new Response(html, {
		headers: { "Content-Type": "text/html" },
	});
}

Binary Modules

Binary Modules は、画像などのバイナリデータを ArrayBuffer としてインポートする、非標準の仕組みです。

Pages Functions のコード内でバイナリファイルのデータをインポートする基本的な例です。

import data from "../my-data.bin";

export async function onRequest() {
	return new Response(data, {
		headers: { "Content-Type": "application/octet-stream" },
	});
}

役に立ちましたか?