Webpack将库反应到窗口中的全局变量

时间:2016-01-29 06:50:01

标签: reactjs webpack

我使用webpack来构建React组件。 这是JSX文件:

'lifetime' => 120, // in minutes, default 2 hours

'expire_on_close' => false,

然后,我想在html中调用函数// index.js var React = require('react'); var ReactDOM = require('react-dom'); var renderHelloComponnet = function(id) { ReactDOM.render( <h1>Hello, World!</h1>, document.getElementById(id) ); } 我有webpack的配置文件:

renderHelloComponnet

但是我无法在html中呈现我的组件:

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'] }
            }
        ]
    }
}

我收到错误:<!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>

1 个答案:

答案 0 :(得分:3)

您在module.exports中导出的内容是library var中的内容。因此,如果您index.js导出renderHelloComponent

module.exports = renderHelloComponent;

然后在你的ABC var中你将得到函数:

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

如果您希望library var实际拥有renderHelloComponent方法,则可以使用此函数导出对象:

module.exports = {
    renderHelloComponent: renderHelloComponent
}

然后你就可以做到这一点:

<script>
    ABC.renderHelloComponent('example');
</script>