0

I have a NodeJS project written in TypeScript and I want to change it to generate ES Module so I can use my NodeJS shell with an import statement:

NodeJS Terminal using jQuery Terminal

What I did was adding "type": "module" to package.json and setting up tsconfig.json:

"module": "ES2020",
"target": "ES2020",

(I was asking chatGPT this is what he told me) but when I run my code:

nodemon --transpile-only app.ts

it throws an error:

$ nodemon --transpile-only app.ts
[nodemon] 2.0.22
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: ts,json
[nodemon] starting `ts-node --transpile-only app.ts`
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /home/kuba/projects/jcubic/koduj/akademia/quiz/quiz/app.ts
    at new NodeError (node:internal/errors:400:5)
    at Object.getFileProtocolModuleFormat [as file:] (node:internal/modules/esm/get_format:79:11)
    at defaultGetFormat (node:internal/modules/esm/get_format:121:38)
    at defaultLoad (node:internal/modules/esm/load:81:20)
    at nextLoad (node:internal/modules/esm/loader:163:28)
    at ESMLoader.load (node:internal/modules/esm/loader:605:26)
    at ESMLoader.moduleProvider (node:internal/modules/esm/loader:457:22)
    at new ModuleJob (node:internal/modules/esm/module_job:64:26)
    at ESMLoader.#createModuleJob (node:internal/modules/esm/loader:480:17)
    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:434:34) {
  code: 'ERR_UNKNOWN_FILE_EXTENSION'
}
[nodemon] app crashed - waiting for file changes before starting...

I was trying multiple things (suggested by chatGPT) but none of them worked. ChatGPT suggested adding extensions ts in multiple ways. He also suggested adding nodemon.json file but that also didn't work.

Sorry, I don't have a minimal reproducible example but I think that this is a standard NodeJS typeScript project, you can find the code on GitHub: https://github.com/jcubic/quizerach (without the last ES Module change).

jcubic
  • 61,973
  • 54
  • 229
  • 402
  • I'm not sure it's even possible to start the node shell in "module mode", although trivially easily to execute a script that way. – Jared Smith May 01 '23 at 17:32
  • @JaredSmith it's not a Node Shell. I run express.js App where I execute eval via HTTP request. – jcubic May 02 '23 at 21:05
  • Ugh that's what I get for reading SO questions on my phone. Based on your linked repo looks like you at the very least need to put `"type": "module"` in your `package.json`. Also you could always have a plain `.mjs` Javascript file that imports your `index.js` or equivalent from your build directory for Typescript and use that for your daemon. – Jared Smith May 03 '23 at 17:44
  • @JaredSmith if you read my question you will see that this doesn't work. If I will change the module in package json I no longer can compile my app. – jcubic May 03 '23 at 17:54

0 Answers0