javascriptreactjsbrowserifycommonjsbrowserify-shim

Access a variable defined in a CommonJS library from the global browser scope


I have a "browserified" library which defines some React components, which I would like to load from an HTML page (served from a Rails app), and then instanciate the React components, fed by some data put inside the page by Rails.

(The big picture is: we have a TurboLinks app, and we want to use some React components for very specific parts, needing more reactivity.
The Rails page would so load both React runtime & the needed applicative components lib, and then generate minimal raw JS to instanciate the React component as needed)

All I found were ways to expose external libs variables to my lib, but I would like to expose my variables to global browser scope.

I ended up by exporting the classes in a rather ugly way (window.Stuff = Stuff;) directly from the .jsx source file, but I feel like this code is smelling...

Any suggestion on a better way to achieve such thing?


Solution

  • Either expose the modules in your browserify bundle, e.g.:

    browserify()
      .require('./whatever', {expose: 'whatever'})
    

    Then from the Rails page JS:

    require('whatever');
    

    Or:

    Create a standalone browserify bundle something like this:

    browserify('./entry', {standalone: 'something'})
    

    entry.js

    module.exports = {
      whatever: require('./whatever')
    };
    

    Then from the Rails page JS:

    window.something.whatever;