Error using Typescript / whatwg-fetch / webpack

I am trying to create a simple demo application using Typescript and React with webpack. When I try to add whatgw-fetch to retrieve data from the server, I get this error when starting webpack:

error TS2307: Cannot find module 'whatwg-fetch' 

Error in import line:

 import * as Fetch from 'whatwg-fetch' 

I installed npm dependency and text for typescript

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

My webpack configuration:

 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] }; 

I do not see errors in my IDE (IntelliJ IDEA), and if I change the import to some module that is actually not there, I get another error ( Module not found: Error: Cannot resolve module 'whatwg-fetcha' in C:\dev\[...] ), and my IDE tells me about import is invalid.

Import for basic React works fine with an equivalent setting:

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

Am I missing something?

Thank you for your help.

+7
fetch reactjs webpack typescript
source share
2 answers

After some research (and, in fact, writing the question), it seems that the input for whatwg-fetch in this use case is: Import a module for only side effects (as described on the site: although not recommended, some modules set up some kind of global state, which can be used by other modules. These modules may not have any export, or the consumer is not interested in any of their export.)

So instead

 import * as Fetch from 'whatwg-fetch' 

I used

 import 'whatwg-fetch' 

And I don't get any more errors, and I can use the fetch function in my component. Hope this helps someone else.

+20
source share

Besides the @Antoine solution, I also need to add @types/whatwg-fetch to my project for it to work:

 npm install --save @types/whatwg-fetch 
0
source share

All Articles