首页 文章

React TS2304错误:找不到名称'Component'

提问于
浏览
3

作为 Headers ,我在TypeScript中使用React进行开发 . 但是在编译步骤中,它会抛出一个错误:

Error in /MyMacPath/react_ts_project/node_modules/@types/react-dom/index.d.ts(25, 34):error TS23O4: Cannot find name 'Component'.

然后我搜索并找到了两种方法,第一种是 declare var Component: any ,后面是typescript getting error TS2304: cannot find name ' require' . 另一个是配置 compilerOptions 并添加一个选项:

"types": ["react-dom"]

不幸的是,它们都不起作用 .

以下是我的项目配置文件:

webpack.config.js

module.exports = {
    cache: true,
    watch: true,
    entry: {
        index: './scripts/index.tsx'
    },
    output: {
        filename: './public/[name].dev.js'
    },
    resolve: {
        // Add `.ts` and `.tsx` as a resolvable extension.
        extensions: ['', '.ts', '.tsx', '.js']
    },
    module: {
        loaders: [
            // all files with a `.ts` or `.tsx` extension will be handled by `ts-loader`
            {
                test: /\.tsx?$/,
                exclude: /node_modules/,
                loader: 'ts-loader'
            }
        ]
    }
}

tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es5",
    "sourceMap": true,
    "allowJs": true,
    "jsx": "react",
    "types": ["react", "react-dom", "jquery", "react-router"]
  },
  "include": [
    "./scripts/"
  ],
  "exclude": [
    "node_modules"
  ],
  "compileOnSave": true
}

此外,我已经通过npm安装了@ types / react @ types / react-dom .

真诚的谢谢 .

1 回答

  • 2

    尝试将此添加到您的compilerOptions对象中 . 它对我有用,刚刚遇到同样的问题 .

    "typeRoots": [
      "./node_modules/@types"
    ]
    

相关问题