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:

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:


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.






Leave a Reply

Your email address will not be published. Required fields are marked *