How can I use this React library with React-Rails

2019-07-28 02:53发布

问题:

I came upon this:

https://github.com/ssorallen/turbo-react

And I like what it does, I am just a bit confused about how I use this code within my Rails project that currently uses the React-Rails gem

I am mostly confused about where to put the code so that I can read it into my Rails gem with React Rails. If I paste the main JS file into my vendor/assets folder, I get this message:

Uncaught ReferenceError: global is not defined

I know that I am just fundamentally misunderstanding how to include this kind of JS file into my Rails project.

回答1:

src/turbo-react.js is meant for a Node.js environment, not a browser environment. I see another file, public/dist/turbo-react.min.js, which has been "compiled" to run in a browser (using Webpack). You should copy that file into vendor/assets, then require it in application.js.

The first few lines of src/turbo-react.js gave me some signals that it is for Node.js:

if (global.Turbolinks === undefined) {
  throw "Missing Turbolinks dependency. TurboReact requires Turbolinks be included before it.";
}

var HTMLtoJSX = require("htmltojsx");
var JSXTransformer = require("react-tools");
var React = require("react");

global and require are both Node.js concepts which don't exist in the browser.



回答2:

You are searching for this one I guess: https://github.com/ssorallen/turbo_react-rails

Installation instructions:

  1. Add this line to your application's Gemfile:

    gem 'turbo_react-rails'

  2. Install the updated gems

    $ bundle install

  3. Require turbo-react in a JavaScript file like "application.js" after Turbolinks:

    //= turbolinks //= require turbo-react

That's it. Now if you click any link in your Web-Application it should be loaded via Ajax and use React to replace the tags in your page.