Search code examples
javascriptbrowserifybootstrapping

Inject data in a Browserify app


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?


Solution

  • 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>