# 以下の質問が出てくるので任意で回答 # Would you like to use git to manage this Worker? (y/n) # No package.json found. Would you like to create one? (y/n) # Would you like to use TypeScript? (y/n) # Would you like to create a Worker at my-worker/src/index.ts? (y/n) 今回は作成した。
一旦起動してますが、作成されているファイルを確認。
my-worker/src/index.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/** * Welcome to Cloudflare Workers! This is your first worker. * * - Run `wrangler dev src/index.ts` in your terminal to start a development server * - Open a browser tab at http://localhost:8787/ to see your worker in action * - Run `wrangler publish src/index.ts --name my-worker` to publish your worker * * Learn more at https://developers.cloudflare.com/workers/ */
asyncfunctionhandleEvent(event) { try { // Add logic to decide whether to serve an asset or run your original Worker code returnawaitgetAssetFromKV(event); } catch (e) { let pathname = newURL(event.request.url).pathname; returnnewResponse(`"${pathname}" not found`, { status: 404, statusText: "not found", }); } }
wrangler.toml にホストさせるファイルのパスを設定。
my-site/wrangler.toml
1 2 3 4 5 6
name = "my-site" main = "src/index.ts" compatibility_date = "2022-05-14"
/** * The DEBUG flag will do two things that help during development: * 1. we will skip caching on the edge, which makes it easier to * debug. * 2. we will return an error message on exception in your Response rather * than the default 404.html page. */ constDEBUG = false;
asyncfunctionhandleEvent(event) { let options = {};
/** * You can add custom logic to how we fetch your assets * by configuring the function `mapRequestToAsset` */ // options.mapRequestToAsset = handlePrefix(/^\/docs/)
return response; } catch (e) { // if an error is thrown try to serve the asset at 404.html if (!DEBUG) { try { let notFoundResponse = awaitgetAssetFromKV(event, { mapRequestToAsset: (req) => newRequest(`${new URL(req.url).origin}/404.html`, req), });
/** * Here's one example of how to modify a request to * remove a specific prefix, in this case `/docs` from * the url. This can be useful if you are deploying to a * route on a zone, or if you only want your static content * to exist at a specific path. */ functionhandlePrefix(prefix) { return(request) => { // compute the default (e.g. / -> index.html) let defaultAssetKey = mapRequestToAsset(request); let url = newURL(defaultAssetKey.url);
// strip the prefix from the path for lookup url.pathname = url.pathname.replace(prefix, "/");
// inherit all other props from the default request returnnewRequest(url.toString(), defaultAssetKey); }; }
$ npx create-remix@latest ? Where would you like to create your app? remix-app ? What type of app do you want to create? Just the basics ? Where do you want to deploy? Choose Remix if you're unsure; it's easy to change deployment targets. Cloudflare Workers ? Do you want me to run `npm install`? Yes ? TypeScript or JavaScript? TypeScript