cloudflare / templates

A collection of starter templates and examples for Cloudflare Workers and Pages
https://cloudflareworkers.com
MIT License
1k stars 638 forks source link

TypeScript example #22

Closed balupton closed 2 years ago

balupton commented 5 years ago

It would be nice for a typescript example of workers. As right now, I can't seem to find any type definitions for the most basic example:

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

/**
 * Fetch and log a given request object
 * @param {Request} request
 */
async function handleRequest(request) {
  console.log('Got request', request)
  const response = await fetch(request)
  console.log('Got response', response)
  return response
}

https://github.com/zeit/ncc could probably be used for generating the compiled bundle, as it supports typescript

jrf0110 commented 5 years ago

For basic examples, you can follow the instructions here https://blog.cloudflare.com/using-webpack-to-bundle-workers/

Cloudflare Workers are a superset of Service Workers, so you can use TypeScript's built-in definitions for webworkers by specifying it in your tsconfig.json:

"lib": ["es2015", "webworker"],
13rac1 commented 5 years ago

I've published complete types and mock: https://github.com/udacity/cloudflare-typescript-workers

cryptiklemur commented 5 years ago

would be nice to update that blog post to use babel-loader (the defacto standard for typescript + webpack now), instead of awesome-typescript-loader

leoiii12 commented 4 years ago

This is in parceljs https://github.com/leoiii12/cloudflare-workers-forum/tree/master/api/

lukeed commented 2 years ago

I know this is old, but this is now available in the /worker-typescript subdirectory.

You can create a project with it by visiting https://workers.new/typescript or locally via:

$ npm init cloudflare my-project worker-typescript
# or
$ yarn create cloudflare my-project worker-typescript
# or
$ pnpm create cloudflare my-project worker-typescript