【问题标题】:Getting Unexpected token with react-rails es6使用 react-rails es6 获取意外令牌
【发布时间】:2016-08-27 06:52:31
【问题描述】:
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;

宝石文件

gem "browserify-rails"
gem 'react-rails

config/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

Unexpected token 指的是第一个&lt;div&gt;,为什么?

【问题讨论】:

  • 请写出解决方案,我也有同样的问题。
  • @SergeijBelevskij 4 个月似乎是 4 年前;我几乎记不得了。我想我跑了rails assets:precompile

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


【解决方案1】:

JSX 语法没有被编译,可能是因为你需要将 react babel 预设添加到你的 browserify 配置中。

安装包:

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

config/application.rb

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

【讨论】:

  • 我在我的package.json 文件中有这个,通过你的browserify 配置我得到:Couldn't find preset "es2015," relative to directory
  • 对不起,我觉得预设名称之间没有逗号,所以[ es2015 react ]
  • 是的config.browserify_rails.commandline_options = "-t [ babelify --presets [ es2015 react ] ]" 我也有.babelrc 和{ "presets": ["es2015"] } 但同样的问题
  • 去掉 es2015 之间的逗号并在你的 commandline_options 中做出反应。
  • 你发现了吗?我有同样的问题
猜你喜欢
  • 2017-11-05
  • 1970-01-01
  • 2018-09-13
  • 2019-03-21
  • 2019-06-24
  • 1970-01-01
  • 2017-02-01
  • 1970-01-01
  • 2018-01-20
相关资源
最近更新 更多