【问题标题】:React Typescript Component Unexpected token, expected "{"反应打字稿组件意外的令牌,预期的“{”
【发布时间】:2021-06-01 22:52:07
【问题描述】:

我有一个打字稿中的反应应用程序,由于未知原因无法编译。这是我得到的错误:

./src/App.tsx
SyntaxError: C:\Users\LANAUS\repos\gdn-tabular-app\src\src\App.tsx: Unexpected token, expected "{" (12:34)

  10 | 
  11 | // Web socket client connection
> 12 | export class App extends Component<any, any> {
     |                                   ^
  13 |     index = 0
  14 |     connections: httpLib.ClientRequest[];
  15 |     tlm: AxiosInstance;

我不明白为什么类定义中的 似乎有问题。据我所知,它似乎正在将 JS 规则应用于我的 TSX 文件。作为测试,当我删除 然后错误变成:

./src/App.tsx
SyntaxError: C:\Users\LANAUS\repos\gdn-tabular-app\src\src\App.tsx: Unexpected token (14:15)

  12 | export class App extends Component {
  13 |     index = 0
> 14 |     connections: httpLib.ClientRequest[];

我在这里完全不知所措,有谁知道为什么编译失败?

其他相关文件:

.babelrc

{
    "presets": [
        "@babel/preset-env",
        "@babel/preset-react"
    ],
    "plugins": [
        [
            "@babel/plugin-transform-react-jsx",
            {
                "runtime": "automatic"
            },
            "@babel/plugin-proposal-class-properties"
        ]
    ]
}

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react",
    "suppressImplicitAnyIndexErrors": true
  },
  "include": [
    "src"
  ]
}

【问题讨论】:

  • 您好像缺少 babel 的 typescript 插件?
  • @FelixKling 如果你指的是@babel/preset-typescript,我已经尝试过了,它会导致 npm start 在Files successfully emitted, waiting for typecheck results...上冻结
  • 我无法对此发表评论,我只能说,如果您希望 babel 理解 typescript 代码,您需要加载适当的插件(就像您为 JSX 所做的那样)。或者你可以先把Typescript文件编译成JS文件,直接用Typescript编译器。
  • 你也在使用 WebPack 吗?哪个是配置文件?您还使用哪个命令来运行项目?关于这个问题,正如@FelixKling 提到的,你应该有@babel/preset-typescript,在这种情况下,问题应该是为什么它被上面的消息冻结了。

标签: javascript node.js reactjs typescript compiler-errors


【解决方案1】:

不要听过去的我,过去的我在这个问题上已经 2 周了,无法思考。 Felix Kling 说得对,我需要 .babelrc 中的 babel 预设 (@babel/preset-typescript)。

它似乎在Files successfully emitted, waiting for typecheck results... 消息上冻结的原因是因为该应用程序正在运行,如果我检查了我的浏览器,我会看到该应用程序。我所做的某些事情一定抑制了我通常在此消息之后看到的警告。

【讨论】:

    猜你喜欢
    • 2020-06-11
    • 1970-01-01
    • 1970-01-01
    • 2019-08-07
    • 2021-11-10
    • 2019-02-26
    • 2018-04-01
    • 2020-11-15
    • 1970-01-01
    相关资源
    最近更新 更多