简体   繁体   中英

Accessing webpack/bundled React Class from .html file

Is it not possible to access already 'built' components within the html file that the build is linked to?

I am trying the following -

In bundle.js

var React = require('react');
var ReactDOM = require('react-dom');

     var Titles = React.createClass({
       render() {

          return (
             <div>
                <h1>{this.props.headerProp}</h1>
                <h2>{this.props.contentProp}</h2>
             </div>
          );
       }
    });

In my html page -

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/JSXTransformer.js"></script>

    <div id="con"></div>
        <script type="text/javascript" src="/public/bundle.js'"></script>

      <script type="text/jsx">

    ReactDOM.render(<Titles headerProp = "Header from props..." contentProp = "Content
       from props..."/>, document.getElementById('con'));
        </script>

But console outputs React is not defined.

I have even tried to set react globally within the bundle -

window.React = React;

And calling it with window. prefixed but yields the same result.

Because you're mentiong a bundle.js file with a snippet containing commonjs style imports, I'm assuming you're using Webpack.

I have some considerations about your code.

  1. bundle.js file will not expose any module as global. That includes React and any other module you might require inside the bundle. There isn't goint to be window.ModuleName . However, these module are accessible in the Browser via require.js because Webpack will export modules as UMD, that is, they will be accessible through either commonjs or AMD (Require.js).
  2. I'm pretty sure that, if in the entry point of your webpack configuration file, you do something like var React = require("react"); window.React = React var React = require("react"); window.React = React , that's actually going to work.
  3. There's a Webpack module meant to expose modules globally (like in window.x ) in a more ellegant way than (2) called expose-loader . You should take a look at it.
  4. You should really try to avoid doing what you're trying to do. In your entry.js file (the entry point of your webpack configuration) should be responsible for doing something like ReactDOM.render(..., document.getElementById("#app")) . So that, just by including your bundle, the app will render automatically . This is what everybody does.
  5. JSXTransformer.js as well as the <script type="text/jsx"> have been deprecated a long time ago. Now you're supposed to use Babel to compile React.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM