gatsbyJS:错误TS2451:无法重新声明块作用域变量'react_1'

时间:2019-02-11 15:17:48

标签: javascript reactjs typescript gatsby

我正在尝试将打字稿与gatsbyjs中的自定义路由集成在一起,如下所示:

require("source-map-support").install();
require("ts-node").register();

exports.createPages = require("./src/createPages");

tsconfig.json

{
  "include": ["./src/**/*"],
  "compilerOptions": {
    "target": "esnext",
    "module": "commonjs",
    "lib": ["es2015", "es2017"],
    // "allowJs": true,
    // "checkJs": true,
    "jsx": "react",
    "strict": false,
    "esModuleInterop": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "noEmit": true,
    "skipLibCheck": true
  }
}

gastby-config.js

  plugins: [
    `gatsby-plugin-typescript`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        path: `${__dirname}/src/templates`,
        name: "markdown-pages"
      }
    },
    `gatsby-transformer-remark`,
    `gatsby-plugin-sass`,
    `gatsby-plugin-react-svg`
  ]
};

但是当我尝试导入位于 routes 文件夹中的自定义路由时,出现以下错误:

src/Layout.tsx(6,7): error TS2451: Cannot redeclare block-scoped variable 'react_1'.

我使用的路线

import Index from "../pages";

const routes = {
  home: {
    path: "/",
    component: Index
  }

};

// Same keys as 'routes', but the value is only the path.
const paths = Object.keys(routes).reduce((acc, route) => {
  acc[route] = routes[route].path;
  return acc;
}, {});

export { routes, paths };

和createPages组成:

import { routes } from "./routing";

const createPages = ({ actions, graphql }) => {
  const { createPage } = actions;

  Object.keys(routes).forEach(route => createPage(routes[route]));
};

export default createPages;

Layout.tsx

import React from "react";
import Footer from "./Footer";
import Header from "./Header";
import "./scss/style.scss";
import "./logo.css";

const Layout: React.SFC<any> = props => {
  return (
    <>
      <Header />
      {props.children}
      <Footer />
    </>
  );
};

export default Layout;

由于我是gatsby的新手,所以我遵循https://dev.to/hugecoderguy/routing-with-gatsby-and-react-4dlh来集成路由。但这与打字稿结合似乎会产生一些打字稿错误。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

固定如下:

  • 对组件进行了如下更改:resolve(__dirname, "../components/pages/IndexPage.tsx")
  • tsconfig至:
{
  "compilerOptions": {
    "outDir": "./dist/",
    "sourceMap": true,
    "noImplicitAny": false,
    "module": "commonjs",
    "target": "esnext",
    "jsx": "react",
    "lib": ["dom", "es2015", "es2017"],
    "allowSyntheticDefaultImports": true
  },
  "include": ["./src/**/*"]
}

希望它对以后的人有所帮助。