跳转到内容
搜索文档

模块

最后更新 查看 MarkdownAgent 设置

启用模块

Miniflare 同时支持编写 Worker 的传统 service-worker 格式和较新的 modules 格式。要使用 modules 格式,可以通过以下方式启用:

const mf = new Miniflare({
	modules: true,
});

然后你可以像下面这样使用 modules Worker 脚本:

export default {
	async fetch(request, env, ctx) {
		// - `request` 是传入的 `Request` 实例
		// - `env` 包含绑定 (bindings)、KV 命名空间、Durable Objects 等
		// - `ctx` 包含 `waitUntil` 和 `passThroughOnException` 方法
		return new Response("Hello Miniflare!");
	},
	async scheduled(controller, env, ctx) {
		// - `controller` 包含 `scheduledTime` 和 `cron` 属性
		// - `env` 包含绑定、KV 命名空间、Durable Objects 等
		// - `ctx` 包含 `waitUntil` 方法
		console.log("Doing something scheduled...");
	},
};

模块规则

Miniflare 支持所有模块类型:ESModuleCommonJSTextData 以及 CompiledWasm。你可以指定附加的模块解析规则,如下所示:

const mf = new Miniflare({
	modulesRules: [
		{ type: "ESModule", include: ["**/*.js"], fallthrough: true },
		{ type: "Text", include: ["**/*.txt"] },
	],
});

默认规则

以下规则会自动追加到你的模块规则列表末尾。你可以通过指定匹配相同 globs 的规则来重写它们:

[
	{ type: "ESModule", include: ["**/*.mjs"] },
	{ type: "CommonJS", include: ["**/*.js", "**/*.cjs"] },
];

这篇文档对您有帮助吗?