React is undefined (Cannot read property 'createElement' of undefined)

Viewed 10544

I'm trying to convert a working ReactJS application into TypeScript, and I've had some issues getting anything to work properly.

import React from "react";
import * as ReactDOM from "react-dom";
import Application from "./Application";

console.log(React); // undefined

ReactDOM.render(
    <Application/>, window.document.getElementById("application-wrapper")
);

The console throws an error at <Application />

When I import react like this, react loads:

import * as React from "react";

However, I want to use the import statement using the default export, because I import React using this import syntax in all the existing components:

import React, {Component} from "react";

export default class Whatever extends Component<Props, State> {
...
}

My tsconfig.json file contains this line allowing synthetic defaults:

"allowSyntheticDefaultImports": true

My webpack.config.js file:

let path = require("path");
let config = {
    entry: "./src/main.tsx",
    output: {
        path: path.resolve(__dirname, "build"),
        filename: "bundle.js"
    },
    devtool: "source-map",
    resolve: {
        extensions: [".ts", ".tsx", ".js", ".jsx"]
    },
    module: {
        loaders: [
            {
            test: /\.tsx?$/,
            loader: "ts-loader",
            exclude: /node_modules/
            }
        ]       
    }
};

module.exports = config;

Not sure what I'm missing here....

3 Answers

Set "esModuleInterop": true instead.

In your typescript configuration i.e tsconfig.json "esModuleInterop": true and "allowSyntheticDefaultImports": true. this will allow you to import CommonJS modules in compliance with es6 modules spec.

Related