Skip to main content
 首页 » 编程设计

python之webpack bundle export 中的 React 组件库,用于运行时渲染

2024年10月17日41cmt

我正在升级旧版 web2py (python) 应用程序以使用 React 组件。我正在使用 webpack 将 jsx 文件转换为缩小的 js 包。我希望能够使用:

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

其中 ComponentA 包含在 bundle 中,bundle 包含在 web2py View 中。问题是我无法在 View 中访问 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-loader和 webpack-add-module-exports但我还没有让它工作。非常感谢任何帮助。

请您参考如下方法:

遇到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 View 中(确保包含构建文件,例如 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> 

注意:我决定在 View 中使用 vanilla react 而不是 JSX,因此无需在浏览器中进行额外的转译。