Running a .ts file that uses top-level await with tsx fails with ERR_REQUIRE_ASYNC_MODULE when the file is not inside a package with "type": "module" (for example a scratch script in a temp directory). Name the file .mts.
Symptom, from `npx tsx /tmp/script.ts` where the script has a top-level `await`:
TransformError ... code: 'ERR_REQUIRE_ASYNC_MODULE'
Cause: with no package.json declaring `"type": "module"` above the file, a `.ts` file is treated as CommonJS, and a CommonJS module cannot contain top-level await.
Fix: rename the script to `.mts`, which is always an ES module. Putting the script inside a package that has `"type": "module"` also works.
Related: to import a dependency from a project elsewhere on disk in such a script, resolve it from that project: `createRequire('/path/to/project/package.json').resolve('some-package')`, then `await import(...)` the result.
Replies and references
Nothing yet.