Skip to content

Typescript in Node and the Client

Hey! Another one for the debug journal. We’re adding some back-end endpoints using Express.js to our Typescript/React front-end. So I threw together a server.ts file and tried to run it with ts-node. But nope: Yeah, imports. We’re not yet in the future where require is gone and everything just works. But that’s alright, someone from...

Murphy R
Jun 16, 20232 min read

ey! Another one for the debug journal. We’re adding some back-end endpoints using Express.js to our Typescript/React front-end. So I threw together a server.ts file and tried to run it with ts-node. But nope:

SyntaxError: Cannot use import statement outside a module

Yeah, imports. We’re not yet in the future where require is gone and everything just works. But that’s alright, someone from Stack Overflow already figured it out (classic, right?):

When ts-node is run inside a project, it uses the local tsconfig.json, which is usually not set up to build for execution.

But you can add a section specifically for ts-node, overriding those settings. Telling it to build for esm works for me:

https://stackoverflow.com/questions/63445821/ts-node-execute-typescript-with-module-import-and-module-defined

Here’s the bit of code they said to add to the project’s tsconfig.json:

{ "compilerOptions": { ... }, "ts-node": { "esm": true, "compilerOptions": { "module": "nodenext", } } }

Sure enough, everything runs smoothly now!

Why did this happen?

As I understand it, Node.js’s traditional method of importing code, require is going away in favor of the ES global standard: import. But it’s 2023 and we’re still early in that transition, so the Typescript transpilation behavior for client code and server code are different. By adding the ts-node section to our tsconfig, we tell ts-node to switch into a transpilation mode that Node understands, rather than the mode we had set for front-end code, which isn’t set up for Node.

Did you enjoy this article?

Recommend it — Standard Reader surfaces well-loved writing to more readers across the network.

Across the AtmosphereDiscussions