A
A
Alesha2018-11-29 13:12:23
JavaScript
Alesha, 2018-11-29 13:12:23

How to use the import directive in a browser?

There is just an example in which I use React:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Add React in One Minute</title>
  </head>
  <body>

    <h2>Add React in One Minute</h2>
    <p>This page demonstrates using React with no build tooling.</p>
    <p>React is loaded as a script tag.</p>

    <p>
      This is the first comment.
      <!-- We will put our React component inside this div. -->
      <div class="like_button_container" data-commentid="1"></div>
    </p>

  </body>
<script src="https://unpkg.com/[email protected]/umd/react.production.min.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.production.min.js"></script>

<script type="text/javascript">
import React, { Component } from 'react';

const e = createElement;
class LikeButton extends Component {
  constructor(props) {
    super(props);
    this.state = { liked: false };
  }
  render() {
    let isLiked = localStorage.getItem("likedState") || this.state.liked;
    if (isLiked) {
      return 'You liked comment number ' + this.props.commentID;
    }
    return e(
      'button',
      { onClick: () => { localStorage.setItem("likedState", true); this.setState({ liked: true })} },
      'Like'
    );
  }
}
document.querySelectorAll('.like_button_container')
  .forEach(domContainer => {
    const commentID = parseInt(domContainer.dataset.commentid, 10);
    ReactDOM.render(
      e(LikeButton, { commentID: commentID }),
      domContainer
    );
  });
</script>
</html>

There is a server part (in Java) that processes the js code from this example and substitutes the already transpiled code there:
init("var babelWrapper=function(bwc){return Babel.transform(bwc," +
    "{" +
    "presets:['es2015', 'react', 'stage-1']," +
    "sourceMaps:" + (isDev ? "'inline'" : "false") + "," +
    "comments: " + isDev + "," +
    "plugins:['" + Optional.ofNullable(module)
        .map(s -> "transform-es2015-modules-" + s)
        .orElse(ARROW_SUPPORT_PLUGIN)
    + "']" +
    "}).code;}", javaScriptFileName());

After transpiling the code, an error in the browser - require is not defined. I connect transform-es2015-modules-amd for babel + requirejs - no errors, but the code does not work (although it is transpiled correctly).
Actually, how can I make the browser understand constructs like import React, { Component } from 'react'; ?
However, I can't use npm or webpack or tools like Browserify (or I just don't understand how to use them on the server side, which is written in Java).

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question