2016-06-12 138 views
7

我正在尝试使用Typescript和React与webpack一起工作的简单演示应用程序。当我尝试添加whatgw取到从服务器获取数据,我跑的WebPack时出现此错误:使用Typescript/whatwg-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告诉我导入是无效。

基本阵营优良工程用等效设置进口:

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

我缺少的东西?

感谢您的帮助。

回答

20

经过一些研究(并且实际上写下了这个问题)之后,似乎whatwg-fetch的打字就出现在这个用例中:Import a module for side-effects only(如网站所述:虽然不推荐实践,但某些模块设置了一些可以由其他模块使用的全局状态。这些模块可能没有任何出口,或者消费者不感兴趣,他们的任何出口。)

所以不是

import * as Fetch from 'whatwg-fetch' 

我用

import 'whatwg-fetch' 

而且我不会再有任何错误,我可以在我的组件中使用获取功能。希望这可以帮助别人。

+0

嗨,我试过相同,但它告诉我取在运行时没有定义。任何解决方案 –

+0

你需要使用github shim来为不支持它的浏览器填充它:https://github.com/github/fetch @SalmanHasratKhan – BentOnCoding

+0

只是在照顾你正在使用打字稿,并得到“承诺没有定义“错误,请确保您的tsconfig文件中的目标是”es6“或以上。 – user31208

0

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

npm install --save @types/whatwg-fetch