Taras Yaremkiv Taras Yaremkiv - 5 days ago 6
React JSX Question

What do I misunderstand about import in ES6?

I've done very simple markdown previewer using mark library in React. At first I did it by adding scripts to my Index.html in the tag.

<body>
<div id="root"></div>
<script src="https://unpkg.com/react@latest/dist/react.js">
<script src="https://unpkg.com/react-dom@latest/dist/react-dom.js">
<script src="https://npmcdn.com/babel-core@5.8.38/browser.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/marked/0.3.6/marked.min.js"></script>
<script type="text/babel" src="script.js" ></script>
</body>


Everything works fine, but when I removed strings with react.js and react-dom.js, and added them to the script.js as below, I saw an error in console:
console error

import React from "react.min"
import ReactDOM from "react-dom.min"
class Input extends React.Component {
constructor(props) {
super(props);
this.state = {
_text: "",
};
}

handleChange(e) {
this.setState({
_text: marked(e.target.value)
});
}

createMarkup() {
let outPutVal = this.state._text ? this.state._text : this.state._init;
return {
__html: outPutVal
};
}

render() {
return (<form className="headDiv">
<textarea onChange={this.handleChange.bind(this)}
placeholder="Remember, be nice!"
id="inputText" rows="25" cols="100">{this.state._text}</textarea>
<output id="outputText" dangerouslySetInnerHTML={this.createMarkup()} />
</form>);
}
}

ReactDOM.render(<Input/>, document.getElementById("root"));

Answer

When using JS modules, Babel only handles the translation of import statements into CommonJS require calls - you still need a module loader of some kind to actually handle linking them all up.

Some examples of tools you could use for this are:

That said, since you have the libraries included as script tags in your page, just removing the imports entirely would probably fix your issue - that approach really doesn't scale well though, so I encourage you to look into the above tools!

Comments