Wrangler complaining about default module export

523 Views Asked by At

When I run

$ node_modules/.bin/wrangler publish --keep-vars --dry-run

I see the following warning:

▲ [WARNING] The entrypoint index.js has exports like an ES Module, but hasn't defined a default export like a module worker normally would. Building the worker using "service-worker" format...

I've configured ES6 modules like so:

$ grep -E '["-]module' package.json
        "test": "NODE_OPTIONS=--experimental-vm-modules node_modules/.bin/jest",
    "type": "module",

My index.js defines two functions, exported so I can test them from index.test.js, and adds an event listener:

export function bar {
    return "https://stackoverflow.com/questions/ask"
}

export async function foo {
    return new Response(JSON.stringify({url: bar()}
}

addEventListener("fetch", (event) => {
    event.respondWith(foo(event.request))
})

How should I address the warning?

1

There are 1 best solutions below

0
On BEST ANSWER

In Workers, addEventListener("fetch", ...) is used when using "Service Workers syntax". Workers also supports an alternative syntax based on ES modules. When Wrangler sees you have exports in your script, it assumes you are using this new modules syntax.

To write your event handler in the new syntax, remove this:

addEventListener("fetch", (event) => {
    event.respondWith(foo(event.request))
})

and replace it with this instead:

export default {
  async fetch(request, env, ctx) {
    return foo(request);
  }
}

This is equivalent to what you had before, but using the new modules-based syntax. The Workers platform will see that you have a default export with a fetch method and will use that to deliver fetch events to your worker, rather than use an event handler.

For more on migrating to modules syntax, see: https://developers.cloudflare.com/workers/learning/migrating-to-module-workers/