【问题标题】:Cannot run ts-node with .tsx files无法使用 .tsx 文件运行 ts-node
【发布时间】:2023-01-10 23:43:47
【问题描述】:

我已经使用 Typescript 和 JSX 创建了一个 React 应用程序(创建 .tsx 文件而不是 .ts),我试图在一个带有热重载的 docker 容器中运行但收效甚微。

我尝试将 nodemon 与 ts-node 结合使用,但一直遇到错误

[ERR_UNKNOWN_FILE_EXTENSION]:未知文件扩展名“.tsx”

一个建议是从 package.json 文件中删除 "type": "module" 但这会导致错误;

SyntaxError: 不能在模块外使用 import 语句

我在 this questionthis one 之间陷入了循环

有谁知道如何解决让 ts-node 与 tsx 文件一起工作的这个特定问题,或者更一般地如何在 docker 容器中使用 JSX 启用 typescript 的热重新加载?

【问题讨论】:

    标签: typescript docker jsx tsx ts-node


    【解决方案1】:
    • 尝试在你的tsconfig.json中将compilerOptions.module设置为CommonJS
    • 不要将"type": "module" 放入package.json

    概念证明: 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://stackoverflow.com/questions/51610583/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);
    

    yarn ts-node src/index.tsx运行

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-10
      • 2018-06-24
      • 2019-11-05
      • 1970-01-01
      • 1970-01-01
      • 2021-11-05
      相关资源
      最近更新 更多