Try   HackMD
tags: web

Use typescript in node with ESM

Background

Migarte the frontend query logic as a sql.

Issue

  1. Not able to use native browser function. need to migrate it to node env

  2. Native node module does not support typescript

Setting

Keep in mind that you need to use ts-node 10+ and NodeJS 12+ in order to use the setup below.

tsconfig.json

{
    "compilerOptions": {
        "lib": ["es2020"],
        "module": "ESNext",
        "moduleResolution": "node",
        "target": "ES2020",
        "esModuleInterop": true,
        ...
    },
    ... 
}

package.json

"scripts": {
  "start": "node --experimental-specifier-resolution=node --loader ts-node/esm ./target-file.ts "
},
...
{ 
    ...
    "type":"module",
    ...
}

It is not recommended to use ts-node in production, so this is very handy and useful for a development environment but make sure to transpile and use the resulting code in production to avoid possible memory issues with TS Node.

Reference

https://stackoverflow.com/questions/63742790/unable-to-import-esm-ts-module-in-node

https://stackoverflow.com/questions/70063451/cant-import-node-fetch-into-typescript