Ignacio Zsabo

Using ts-node and modules in NodeJS 16+ thumbnail

Using ts-node and modules in NodeJS 16+

1 minute of read
NodeJS
ESModules
Typescript

If you are a Front-end developer like me you will be used to using ECMAScript modules all the time to import your files or components, in Node.js this is possible since v13.2.0 experimentally under a flag and right at the time of writing this post version v18.6.0 the ECMAScript modules have a Stability: 2 - Stable tag which means that if we add a key “type”: “module” in the package.json of our project we will be able to use ECMAScript modules, but what if you want to do this while using typescript/ts-node at the same time?

What is ts-node?

To avoid describing it inaccurately, I will extract how they themselves describe what ts-node is:

“ts-node is a TypeScript execution engine and REPL for Node.js.

It JIT transforms TypeScript into JavaScript, enabling you to directly execute TypeScript on Node.js without precompiling. This is accomplished by hooking node’s module loading APIs, enabling it to be used seamlessly alongside other Node.js tools and libraries.”

Problem using both

When you try to use ts-node and your package.json determines that you will use ESModules with "type": "module" your console may display the following error: TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts"

This is because ts-node doesn’t quite accept that you use “type”: “module” in your package.json.

Solutions

the first thing we can imagine is to replace that key in your package.json to commonjs which would solve the problem.

{
	"type": "commonjs",
}

But if like in my case, you need to have the key in your package.json, there is still an experimental option that you can use to be able to run ts-node with your project written in ESModules.

Remember to change the path of your file to execute in my case is index.ts

node --loader ts-node/esm --experimental-specifier-resolution=node index.ts

This will display a warning that you should be aware of because these experimental flags are subject to change in the future.

This way you will be able to use Typescript and execute your ESModules code with ts-node in the same way as you would with node without sacrificing tedious methods.