使用react-rails es6获取意外的令牌

时间:2016-08-27 06:52:32

标签: ruby-on-rails reactjs ecmascript-6 ruby-on-rails-5

Rails 5.0.0.1
Ruby 2.3.1

我认为这可能是一个礼物问题但又一次,它适用于与the tutorial Im following一起创建this的人。所以,没什么特别的:

的application.js

//= require jquery
//= require jquery_ujs
//= require turbolinks
//= cable
//= require_self
//= require react_ujs

window.$ = window.jQuery = global.$ = require('jquery');
var React = window.React = global.React = require('react');
var ReactDOM = window.ReactDOM = global.ReactDOM = require('react-dom');

require('./components');

Components.js

require( 'babel-polyfill' );
// Manually add components to window and global
// so that react_ujs and react-server can find them and render them.
window.Home = global.Home = require("./components/Home.js").default
// same issue if use *.es6.jsx

Home.js(或es6.jsx)

import React from 'react';
import ReactDOM from 'react-dom';

class Home extends React.Component {
  render() {
    return (
      <div className="form-control">
        Home baby
      </div>
    )
  }
}
export default Home;

的Gemfile

gem "browserify-rails"
gem 'react-rails

配置/ application.rb中

# Configure Browserify to use babelify to compile ES6
config.browserify_rails.commandline_options = "-t [ babelify --presets [ es2015 ] ]"

unless Rails.env.production?
    # Work around sprockets+teaspoon mismatch:
    Rails.application.config.assets.precompile += %w(spec_helper.js)

    # Make sure Browserify is triggered when
    # asked to serve javascript spec files
    config.browserify_rails.paths << lambda { |p|
        p.start_with?(Rails.root.join("spec/javascripts").to_s)
    }
end

NPM

npm install browserify browserify-incremental babelify babel-preset-es2015 --save

意外令牌是指第一个<div>,为什么?

1 个答案:

答案 0 :(得分:0)

JSX语法未编译,可能是因为您需要将反应字母预设添加到browserify配置中。

安装包:

npm install --save-dev babel-preset-react

配置/ application.rb中

config.browserify_rails.commandline_options = "-t [ babelify --presets [ es2015 react ] ]"