首页 > 解决方案 > Gatsby 错误 ReferenceError:从 JSX 迁移到 Typescript 时未定义 React

问题描述

我有一个 Gatsby 项目,我想将它从 JSX 迁移到 Typescript。我正在遵循本指南来实现这一目标。

Typescript 的配置如下:

tslint.json

{
    "rulesDirectory": "tslint-plugin-prettier",
    "extends": ["tslint:latest", "tslint-react", "tslint-config-prettier"],
    "rules": {
        "prettier": true,
        "jsx-no-multiline-js": false,
        "jsx-no-lambda": false,
        "import-name": false,
        "no-boolean-literal-compare": false
    }
}

tsconfig.json

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

package.json

...
"type-check": "tsc --noEmit",
"lint": "tslint --project ."
...

gatsby-config.js

module.exports = {
    plugins: [
        'gatsby-plugin-tslint', // TSLint
        // TS Plugin. Gatsby already ships with TS
        {
            resolve: 'gatsby-plugin-typescript',
            options: {
              isTSX: true, // defaults to false
              jsxPragma: 'jsx', // defaults to "React"
              allExtensions: true, // defaults to false
            },
        }
    ]
};

运行时出现以下错误gatsby develop

error There was an error compiling the html.js component for the development server.

See our docs page on debugging HTML builds for help https://gatsby.dev/debug-html ReferenceError: React is not defined

  18 |             next: function (result) {
  19 |                 if (_this.lastError || _this.isDifferentFromLastResult(result)) {
> 20 |                     _this.updateLastResult(result);
     | ^
  21 |                     iterateObserversSafely(_this.observers, 'next', result);
  22 |                 }
  23 |             },


  WebpackError: ReferenceError: React is not defined

我正在使用 ES5 格式的 React 导入,如下所示:

import React, { useState } from "react";

标签: node.jsreactjstypescriptgatsby

解决方案


推荐阅读