Inject data in a Browserify app

随声附和 提交于 2019-12-24 05:49:31

问题


Anyone here knows how to inject data into a Browserify app?

I mean, I use Browserify to create a big bundle app.js file.

But when my single page application starts, the server also add some bootstrap data into the HTML page that loads the app, so that the app doesn't have to do ajax requests to the server to get these data.

For now the HTML template rendered by the server to start the app looks like that:

<script type="text/javascript" >
window.bootstrapData = @Html(utils.CustomSerializer.serialize(bootstrapData));
</script>

<script type="text/javascript" src="@{reactAppBaseUrl}/app.js"></script>

And inside app.js (the Browserified single page app), we are using the window.bootstrapData to get that data inside the Browserify bundle.

Is there any elegant way to do this that would not involve a global variable?


回答1:


Use an external require.

When you bundle your app, use the -r option to enable external requiring for a specific service:

browserify -r appBootstrap  > app.js

Then, in a script tag below where you've imported your bundle, require the service and inject the data:

<script type="text/javascript" src="@{reactAppBaseUrl}/app.js"></script>

<script>
  var serializedData = @Html(utils.CustomSerializer.serialize(bootstrapData))
  require('appBootstrap').load(serializedData);
</script>


来源:https://stackoverflow.com/questions/25269359/inject-data-in-a-browserify-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!