How to run Typescript scripts in your Next.js project

If you've ever tried to add Typescript script to one of your Node.js projects to run it on its own from the command line, it's very likely you came across one of these messages:

  • Error [ERR_REQUIRE_ESM]: Must use import to load ES Module:
  • Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.

A quick search on Google doesn't help much. The solutions range from trying a variety of different tsconfig.json configurations and even adding "type": "module" to your package.json file (which would stop Next.js and any other setup from working entirely).

Running a Typescript script with TSX

I managed to find tsx after a lot of useless Googling and testing Stackoverflow answers that simply didn't help. All I had to do was replace my script in my package.json:

"cache": "ts-node lib/file.ts"

With TSX:

"cache": "tsx lib/file.ts"

And that was it! No weird errors, no need to configure a separate tsconfig.json file. Just plug and play!

I'm 99% sure everything that tsx can do can be done in ts-nodeor similar Typescript runners (with the right config and setup). However the big upside of tsx is how no-config it is.

It's really as easy as install and run!

Running a Typescript ESM script with TSX

One footnote: in certain cases your script might need to import a package that has been converted to ES modules. Unless that package also supports CommonJS it's likely you'll be met with an error like this:

❯ yarn run cache

Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: No \"exports\" main defined in <path to your package here>

In these cases all you have to do is to change your file name from file.ts to file.mts and then change your command to:

"cache": "tsx lib/file.mts"

This will tell tsx to run the entire file as an ES module, solving your error!