Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error with Typescript / whatwg-fetch / webpack

I'm trying to have a simple demo app working using Typescript and React, with webpack. When I try to add whatgw-fetch to retrieve data from a server, I get this error when running webpack :

error TS2307: Cannot find module 'whatwg-fetch'

The error is on the import line :

import * as Fetch from 'whatwg-fetch'

I did install the npm dependency and the typing for typescript

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

My webpack configuration is :

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 don't see any error in my IDE (IntelliJ IDEA) and if I change the import to some module that actually is not there, I get a different error (Module not found: Error: Cannot resolve module 'whatwg-fetcha' in C:\dev\[...]), and my IDE tells me the import is not valid.

The 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 ?

Thanks for your help.

like image 284
Antoine Avatar asked Jun 12 '16 22:06

Antoine


1 Answers

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

So instead of

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.

like image 160
Antoine Avatar answered Oct 30 '22 03:10

Antoine