Search code examples
javascriptcloudflare-workers

How do you use ES6 exports in Cloudflare worker scripts?


I'm trying to get familiar with CloudFlare workers.

I've copied a quickstart project from https://developers.cloudflare.com/workers/get-started/quickstarts, via:

wrangler generate my-app https://github.com/cloudflare/worker-template

This gives me a JS file that listens for "fetch" and returns a Response via handleRequest:

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

async function handleRequest(request) {
  return new Response('Hello worker!', {
    headers: { 'content-type': 'text/plain' },
  })
}

Ok, that makes sense.

Now I want to include one of Cloudflare's examples

export default {
  fetch() {
    const html = `<!DOCTYPE html>
      <body>
        <h1>Hello World</h1>
        <p>This markup was generated by a Cloudflare Worker.</p>
      </body>
    `;
    return new Response(html, {
      headers: {
        "content-type": "text/html;charset=UTF-8",
      },
    });
  },
};

This makes less sense. Am I supposed to replace all of the original code with that? If I do, I get an error on wrangler publish:

Error: Something went wrong with the request to Cloudflare... No event handlers were registered. This script does nothing.

Am I supposed to mash them together somehow? How? Is there a step or configuration I'm missing?


Solution

  • The two code snippets in your question use two different syntaxes supported by Workers: Service Workers syntax and ES Modules syntax. addEventListener is used with Service Workers syntax, which was the original syntax supported by Workers. More recently, Workers added support for a new ES-modules-based syntax, which uses export default to export handlers. This new syntax avoids some boilerplate (no weird event.respondWith()) and has some other advantages.

    You need to specify in your wrangler.toml which syntax you are using. To use modules syntax, you'll need to add:

    [build.upload]
    format = "modules"
    main = "./worker.mjs"
    

    See more documentation here.