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

问题描述 投票:1回答:1

我正在升级遗留的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,但我还没有开始工作。任何帮助是极大的赞赏。

python reactjs ecmascript-6 webpack web2py
1个回答
2
投票

我遇到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文件中使用("more" info in the docs) webpack.config.js

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,因此不必在浏览器中进行额外的转换。

© www.soinside.com 2019 - 2024. All rights reserved.