Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript react not importing correctly

I have the following typescript:

import React from 'react'
import ReactDOM from 'react-dom'

const App = () => {
  return (
    <div>
      <p>Hello world!</p>
    </div>
  )
}

ReactDOM.render(<App />, document.getElementById('app'))

It produce the following js:

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const react_1 = require("react");
const react_dom_1 = require("react-dom");
const App = () => {
    return (react_1.default.createElement("div", null,
        react_1.default.createElement("p", null, "Hello world!")));
};
react_dom_1.default.render(react_1.default.createElement(App, null), document.getElementById('app'));
//# sourceMappingURL=react.component.js.map

When running it, I get the following error:

(index):29 Error: (SystemJS) Cannot read property 'render' of undefined
  TypeError: Cannot read property 'render' of undefined

It seems like react_dom_1.default is undefined, but I have no clue why?

like image 826
Murdock Avatar asked Mar 09 '23 20:03

Murdock


1 Answers

Try:

import * as React from 'react'
import * as ReactDOM from 'react-dom'

Update

It worked. Could you maybe explain why the other method does not?

In the Es6 module system there are multiple ways to export and import:

Implicit import (AKA default)

You can export things like:

export default someVar;

And then import it as:

import someVar from "./somemodule"

Explicit import

You can export things like:

export { someVar };

And then import it as:

import { someVar } from "./somemodule";

A module can have multiple exports:

export { someVar1, someVar2 };

You can import multiple entities in one import:

import { someVar, someVar2 } from "./somemodule";

You can also declare aliases at entity level:

import { someVar as A, someVar2 as B } from "./somemodule";

Or at module level:

import * as SomeModule from "./somemodule";

Amd then access the entities:

console.log(SomeModule.someVar);
console.log(SomeModule.someVar2);

You were using the default import from React and ReactDom but those modules expose multiple entities.

like image 90
Remo H. Jansen Avatar answered Mar 21 '23 06:03

Remo H. Jansen