Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack React library to global variable in window

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

like image 680
fudy Avatar asked Sep 25 '22 13:09

fudy


1 Answers

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>
like image 150
dreyescat Avatar answered Sep 28 '22 04:09

dreyescat