This is likely no longer needed, instead use wrangler2's TypeScript option and this will generate an easily deployable skeleton which looks like this example. I'm keeping this in place because the [build] component of wrangler.toml is useful.
To use wrangler2 install it using npm i wrangler, then wrangler init and the instructions while accepting the usage of TypeScript.
Would you like to use TypeScript? (y/n)
An example of using the new style ESModules syntax for a Cloudflare Worker in TypeScript
This is deceptively difficult to do and IMO the current solution is effectively undocumented, key points are that your package.json, *.mts files, tsconfig.json and wrangler.toml all need to be configured correctly.
-
All your TS files that are ES Modules have the extension
.mtsinstead of.ts. -
package.jsondeclares the module correctly
{
...
"type": "module",
"module": "./dist/index.mjs",
...
}tsconfig.jsontargets some modern output, thetypessection contains the CF workers types, which are also in yourdevDependencies.
{
...
"target": "esnext",
"lib": ["esnext"],
"types": ["@cloudflare/workers-types"],
...
}wrangler.toml's[build]and[build.upload]is configured correctly, withmainpointing to the output file, NOTE this by default is appended to.dist/, this can be overriden with adirfile (this is documented deeply within the Clouflare Workers docs),formatwithin[build.upload]is set tomodulesNOTservice-workers,[build]'scommandby default is set to usenpmin most examples, but I changed it toyarnto show how you'd do it.
[build]
command = "yarn install && yarn run build"
[build.upload]
format = "modules"
main = "index.mjs"