reactjs - Webpack React library to global variable in window -


i use webpack build react components. here 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, want call function renderhellocomponnet in html have config file 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 can't render 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 error: typeerror: abc.renderhellocomponnet not function

what export in module.exports in library var. if in index.js export renderhellocomponent:

module.exports = renderhellocomponent; 

then in abc var you'll function:

<script type="text/javascript">     abc('example'); </script> 

if want library var have renderhellocomponent method can export object function inside:

module.exports = {     renderhellocomponent: renderhellocomponent } 

then able this:

<script>     abc.renderhellocomponent('example'); </script> 

Comments