Cannot run ts-node with .tsx files
Asked Answered
D

1

9

I have created a React app with Typescript and JSX (creating .tsx files instead of .ts) which I am attempting to run in a docker container with hot reloads but with little success.

I've tried using nodemon in conjunction with ts-node but keep running into the error

[ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".tsx"

One suggestion was to remove "type": "module" from the package.json file but this leads to the error;

SyntaxError: Cannot use import statement outside a module

I get caught in a loop in SO between this question and this one

Does anyone know how to solve either this specific issue of getting ts-node to work with tsx files or more generally how to enable hot reloading of typescript with JSX inside a docker container?

Doublebreasted answered 11/2, 2022 at 16:17 Comment(1)
@CraZyDroiD as of the time of writing I have not and have since moved around the problem, sorry.Doublebreasted
G
3
  • Try setting compilerOptions.module to CommonJS in your tsconfig.json
  • Don't put "type": "module" in package.json

Proof of concept: https://github.com/ferdinandant/stacko-unknown-ext-tsx


tsconfig.json

{
  "include": ["src", "types/**/*"],
  "exclude": ["node_modules/**"],
  "compilerOptions": {
    "module": "CommonJS",
    "lib": ["dom", "esnext"],
    "rootDir": "./src",
    "jsx": "react",
    "esModuleInterop": true,
    "skipLibCheck": true,
    "noEmit": true
  },
  // https://mcmap.net/q/47764/-ts-node-ignores-d-ts-files-while-tsc-successfully-compiles-the-project
  "ts-node": {
    "files": true
  }
}

package.json

{
  "name": "stacko-unknown-ext-tsx",
  "version": "1.0.0",
  "main": "src/index.tsx",
  "author": "Ferdinand Antonius",
  "license": "MIT",
  "scripts": {
    "dev": "ts-node src/index.tsx"
  },
  "devDependencies": {
    "@types/node": "^18.11.18",
    "ts-node": "^10.9.1",
    "typescript": "^4.9.4"
  }
}

src/index.tsx

import fs from "fs";

console.log("Hello!");
console.log(fs);

Run it as yarn ts-node src/index.tsx

Grueling answered 10/1, 2023 at 15:43 Comment(1)
for me it was the "esModuleInterop": true, that made it happenJunoesque

© 2022 - 2024 — McMap. All rights reserved.