webpack bundle中的react组件库导出以用于运行时渲染

时间:2016-10-04 07:09:55

标签: python reactjs ecmascript-6 webpack web2py

我正在升级遗留的web2py(python)应用程序以使用react组件。我正在使用webpack将jsx文件转换为minified js bundle。我希望能够使用:

ReactDOM.render(
  <ComponentA arg1="hello" arg2="world" />,
  document.getElementById('react-container')
);

其中ComponentA包含在捆绑包中,捆绑包包含在web2py视图中。问题是我无法在视图中访问ComponentA。以下示例将起作用:

<script>
var ComponentA = React.createClass({
     render: function() {
      var p = React.createElement('p', null, 'Passed these props: ',this.props.arg1, ' and ', this.props.arg2);
      var div = React.createElement('div', { className: 'my-test' }, p);
      return div;
  }
});

var component = React.createElement(ComponentA, {arg1:"hello", arg2:"world"})
ReactDOM.render(
  component,//I would rather use <ComponentA arg1="hello" arg2="world" />,
  document.getElementById('react-sample')
);

</script>

我看了exports-loaderwebpack-add-module-exports,但我还没有开始工作。非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

我在遇到this StackOverflow answer

后解决了这个问题

首先确保您的main.jsx文件(将导入所有组件)也导出它们:

import React from 'react';
import ReactDOM from 'react-dom';
import ComponentA from './components/A';
import ComponentB from './components/B';
import style from '../stylesheets/main.scss';

// This is how every tutorial shows you how to get started.
// However we want to use it "on-demand"
/* ReactDOM.render(
  <ComponentA arg1="hello" arg2="world" />,
  document.getElementById('react-container')
);*/

// ... other stuff here

// Do NOT forget to export the desired components!
export {
  ComponentA,
  ComponentB
};

然后确保在output.library文件中使用webpack.config.js ("more" info in the docs)

module.exports = {
    entry: {
        // 'vendor': ['bootstrap', 'analytics.js'],
        'main': './src/scripts/main.jsx'
    },
    output: {
        filename: './dist/scripts/[name].js',
        library: ['App', 'components'] 
// This will expose Window.App.components which will 
// include your exported components e.g. ComponentA and ComponentB
    }
// other stuff in the config
};

然后在web2py视图中(确保包含构建文件,例如main.js和相应的容器):

<!-- Make sure you include the build files e.g. main.js -->
<!-- Some other view stuff -->
<div id="react-component-a"></div>
<div id="react-component-b"></div>
<script>
// Below is how it would be used. 
// The web2py view would output a div with the proper id 
// and then output a script tag with the render block.
ReactDOM.render(
  React.createElement(App.components.ComponentA, {arg1:"hello", arg2:"world"}),
  document.getElementById('react-component-a')
);

ReactDOM.render(
  React.createElement(App.components.ComponentB, {arg1:"hello", arg2:"world"}),
  document.getElementById('react-component-b')
);
</script>

注意:我决定在视图中使用vanilla而不是JSX,因此不需要在浏览器中进行额外的转换。