1

我试图让 Gatsby 使用 TypeScript,按照此处的说明进行操作,但由于某种原因,tsc它没有转换其余 ( ...) 运算符,而是引发以下错误:

 WAIT  Compiling...

 ERROR  Failed to compile with 1 errors

 error  in ./src/components/Input.tsx

Syntax Error: Unexpected token (26:95)

> 26 | const Input = ({ text, ...inputProps }) => (react_1.default.createElement(
     |                        ^

如果我从命令行运行tsc,则文件被正确编译,替换...为对__rest.

这是我的tsconfig.json

{
  "compilerOptions": {
    "outDir": "./dist/"
  },
  "include": [
    "./src/**/*"
  ]
}

如您所见,它非常小。我尝试使用一堆libs (来自Compiler Options)和其他选项,但似乎没有任何效果。

4

1 回答 1

1

您应该添加"target": "es5"到您的tsconfig.json,因为Gatsby 默认为"target": "esnext".

{
  "compilerOptions": {
    "outDir": "./dist/",
    "target": "es5"
  },
  "include": [
    "./src/**/*"
  ]
}

它将指示 TypeScript 将 ES6 代码转换为 ES5。

您尝试的lib选项只会更改 TypeScript 对您的代码进行类型检查的方式。例如,当使用"target": "es5"TypeScript 时将不允许使用,Promise因为它不是 ES5 标准的一部分。

通过添加"lib": ["dom", "es6"]你告诉他编译到 ES5 将使用 ES6 标准库 + DOM API(不是 ECMAScript 的一部分,如document)。

更新,使用 Gatsby 配置:

plugins: [
  {
    resolve: 'gatsby-plugin-typescript',
    options: {
      transpileOnly: true, // default
      compilerOptions: {
        target: 'es5',
        experimentalDecorators: true,
        jsx: `react`
      }, // default
    }
  },
]
于 2017-11-24T21:52:47.773 回答