从html将数据引导到webpack捆绑的javascript中

时间:2021-06-07 14:54:51

I've recently converted a React app from a globals-everywhere script-tag-per-js-file setup into a bundled webpack app (great!).

我最近将一个React应用程序从全局 - 无处不在的script-tag-per-js文件设置转换为捆绑的webpack应用程序(太棒了!)。

However, in the app originally I was able to expose global init functions in the scripts and then have rendered calls in the generated html server from my Scala Play backend. For instance

但是,在应用程序中,我最初能够在脚本中公开全局init函数,然后在我的Scala Play后端生成的html服务器中进行调用。例如

// Component.js
class MyComponent extends React.Component {
    render() {
        <div> {this.props.myData} </div>
    }
}
initComponent(data) {
    ReactDOM.render(
        <MyComponent myData={data} />
    ) 
}

And then in the backend:

然后在后端:

// ComponentPage.scala.html
...
<script> 
  $(() => initComponent(@scala.serverVariable.getData(currentUser))
</script>

Now that my javascript is bundled (and eventually minified/uglified), I don't have any way for the scala backend to know the mangled/eventual name of the function to call. Is there a way to tell webpack to keep certain functions global? Is there a better pattern to use to bootstrap the serverside data into the react component?

现在我的javascript被捆绑(并最终缩小/ uglified),我没有任何方法让scala后端知道要调用的函数的错位/最终名称。有没有办法告诉webpack保持某些功能全局?是否有更好的模式用于将服务器端数据引导到react组件中?

Here are two approaches I've considered:

以下是我考虑过的两种方法:

  • I could make it a loading/complete style component, where there's a spinner and then an ajax call to the server to get the correct data, but since I already have the data available at render time, I'd rather not incur an extra round-trip from client to server.
  • 我可以使它成为一个加载/完整样式组件,其中有一个微调器,然后是一个ajax调用服务器来获取正确的数据,但由于我已经在渲染时获得了数据,我宁愿不再招致额外的一轮 - 从客户端到服务器。
  • I can include the data in a tag with data-attributes and fetch it onDocumentReady, but the serialization/deserialization has limitations for complex objects and this feels quite hacky.
  • 我可以将数据包含在带有data-attributes的标记中,并将其读取到onDocumentReady,但序列化/反序列化对复杂对象有限制,这感觉非常hacky。

1 个解决方案

#1


1  

Simply attach the function to the window object. This will prevent name mangling.

只需将该功能附加到窗口对象即可。这样可以防止名称损坏。

window.initComponent = function(data) {
  ReactDOM.render(
    <MyComponent myData={data} />
  ) 
}

Similarly (for explicitness):

同样(为了明确):

// ComponentPage.scala.html
...
<script> 
  $(() => window.initComponent(@scala.serverVariable.getData(currentUser))
</script>

#1


1  

Simply attach the function to the window object. This will prevent name mangling.

只需将该功能附加到窗口对象即可。这样可以防止名称损坏。

window.initComponent = function(data) {
  ReactDOM.render(
    <MyComponent myData={data} />
  ) 
}

Similarly (for explicitness):

同样(为了明确):

// ComponentPage.scala.html
...
<script> 
  $(() => window.initComponent(@scala.serverVariable.getData(currentUser))
</script>