Typescript / whatwg-fetch / webpack 错误

Error with Typescript / whatwg-fetch / webpack

我正在尝试使用 Typescript 和 React 以及 webpack 制作一个简单的演示应用程序。当我尝试添加 whatgw-fetch 以从服务器检索数据时,我在 运行 webpack :

时收到此错误
error TS2307: Cannot find module 'whatwg-fetch'

错误在导入行上:

import * as Fetch from 'whatwg-fetch'

我确实安装了 npm 依赖项和打字稿

npm install --save whatwg-fetch
typings install --global --save dt~whatwg-fetch

我的 webpack 配置是:

var HtmlWebpackPlugin = require('html-webpack-plugin');
var HTMLWebpackPluginConfig = new HtmlWebpackPlugin({
    template: __dirname + '/app/index.html',
    filename: 'index.html',
    inject: 'body'
});
var path = require('path');
module.exports = {
    entry: [
        path.resolve(__dirname, 'app/index.tsx')
    ],
    output: {
        path: __dirname + '/dist',
        filename: "index_bundle.js"
    },
    resolve: {
        // Add `.ts` and `.tsx` as a resolvable extension. 
        extensions: ['', '.webpack.js', '.web.js', '.ts', '.tsx', '.js']
    },
    module: {
        loaders: [
            {test: /\.tsx$/, exclude: /node_modules/, loader: "ts-loader"}
        ]
    },
    plugins: [HTMLWebpackPluginConfig]
};

我在我的 IDE (IntelliJ IDEA) 中没有看到任何错误,如果我将导入更改为实际上不存在的某个模块,我会得到一个不同的错误 (Module not found: Error: Cannot resolve module 'whatwg-fetcha' in C:\dev\[...]),我的 IDE 告诉我导入无效。

基本 React 的导入在等效设置下工作正常:

npm install --save react
typings install --global --save dt~react
import * as React from 'react'

我错过了什么吗?

感谢您的帮助。

经过更多研究(并实际写下问题),似乎在这个用例中输入 whatwg-fetch:Import a module for side-effects only(如网站上所述:虽然不推荐做法,一些模块设置了一些可以被其他模块使用的全局状态。这些模块可能没有任何导出,或者消费者对它们的任何导出都不感兴趣。)

所以不用

import * as Fetch from 'whatwg-fetch'

我用过

import 'whatwg-fetch'

而且我没有再收到任何错误,我可以在我的组件中使用 fetch 函数。希望这对其他人有帮助。

除了@Antoine 解决方案,我还需要将 @types/whatwg-fetch 添加到我的项目中以使其工作:

npm install --save @types/whatwg-fetch