sanity-io / sanity

Sanity Studio – Rapidly configure content workspaces powered by structured content
https://www.sanity.io
MIT License
5.17k stars 417 forks source link

`sanity exec`: Cannot run `.ts` file when `"type": "module"` is set #5707

Open echocrow opened 7 months ago

echocrow commented 7 months ago

Describe the bug

Sanity CLI provides an exec utility command to run a script. This utility command is more convenient than directly executing a script, because it bootstraps some Sanity config, can prime the access token for getCliClient(), supports TypeScript files, and more.

However, executing a TS file via sanity exec my-file.ts errors out when package.json is configured with "type": "module":

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for ...
    at __node_internal_ (...)
    at ...

Strictly speaking, I believe this is not an issue with sanity exec per-se. I'm not sure how the CLI executes .ts files in CJS mode, but a similar (identical?) issue seems to exist in ts-node. Posting this issue here nonetheless.

To Reproduce

See Stackblitz Repro with instructions in README.md.

Summary:

  1. Initialize a new package and install sanity
  2. Set "type": "module" in package.json
  3. Create a simple my-script.ts file
  4. Attempt to run the script via sanity exec my-script.ts

Expected behavior

The script executes normally.

Which versions of Sanity / Node.js / npm are you using?

Package Version
@sanity/cli 3.28.0
sanity 3.28.0
tyepscript 5.3.3
node 18.18.0
npm 10.2.3

This issue is also present in older Sanity versions and Node 20.

Additional context

Even if this bug is out of scope, maybe there is room to provide an escape hatch in the meantime? That could potentially be:

SimeonGriggs commented 5 months ago

Having just faced the same issue, there is a workaround you could use.

  1. Move your my-script.ts file into a folder, for example scripts
  2. Add a package.json file to that same directory with {"type": "commonjs"}

You should now be able to run sanity exec scripts/my-script.ts

echocrow commented 5 months ago

Add a package.json file to that same directory

I wonder if this would mess with package management/import and/or Typescript config for those script files, assuming a new package.json adds a new package "scope"? will be sure to give this a shot next time we need to exec a script and report back if needed - thanks for the suggestion!