I use webpack to build React components. Here is the JSX file:
// index.js
var React = require('react');
var ReactDOM = require('react-dom');
var renderHelloComponnet = function(id) {
    ReactDOM.render(
      <h1>Hello, World!</h1>,
      document.getElementById(id)
    );
}
Then, I want to call the function renderHelloComponnet in html
I have the config file for webpack:
module.exports = {
    entry: {
        index: './src/index.js'
    },       
    output: {
        path: __dirname + '/build',
        filename: '[name].bundle.js',
        libraryTarget: "var",
        library: ["ABC"],
    },    
    resolve: {
        extensions: ['', '.js', '.jsx']
    },    
    module: {
        loaders: [
            { 
                test: /\.jsx?$/, 
                loader: 'babel-loader',
                exclude: /node_modules/,
                query: { presets:['react'] }
            }
        ]
    }
}
However I can't render my component in html:
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello React!</title>
    <script type="text/javascript" src="./build/index.bundle.js"></script>
  </head>
  <body>
    <div id="example"></div>
    <script type="text/javascript">
        ABC.renderHelloComponnet('example');
    </script>
  </body>
</html>
I get the error: TypeError: ABC.renderHelloComponnet is not a function
What you export in your module.exports is what you get in your library var. So if in your index.js you export renderHelloComponent:
module.exports = renderHelloComponent;
then in your ABC var you'll get the function:
<script type="text/javascript">
    ABC('example');
</script>
If you want your library var to actually have the renderHelloComponent method you can export an object with this function inside:
module.exports = {
    renderHelloComponent: renderHelloComponent
}
Then you will be able to do this:
<script>
    ABC.renderHelloComponent('example');
</script>
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With