How to use React within Rails using coffee?

 ̄綄美尐妖づ 提交于 2020-05-16 03:13:31

问题


I'm adding Reactjs on a Rails application (5.2), but I want to use coffeescript to write it. I've added webpack and installed react and coffee support, and both seems to work, but when I want to use both I get:

Module parse failed: Unexpected token (10:9)
File was processed with these loaders:
 * ./node_modules/coffee-loader/index.js
You may need an additional loader to handle the result of these loaders.
|
| Foo = props(() => {
>   return <div>Hello {props.name}!</div>;
| });
|

I also updated coffeescript to the version 2.0 that should support jsx natively. What could I be missing?


回答1:


I've finally made it work, the problem is that (as @caffeinated.tech mentioned) the configuration is rather tricky.

The required steps to make it work where:

  • Add coffeescript version 2 to the dependencies (by default webpacker installs the version 1).

  • Make sure coffeescript loader is appended to the loader (it is prepended by default):

// config/webpack/environment.js

const coffee =  require('./loaders/coffee')

// instead of environment.loaders.prepend('coffee', coffee)
environment.loaders.append('coffee', coffee)
/// ...
  • And configure coffee-loader to transpile:
// config/webpack/loaders/coffee.js
module.exports = {
  test: /\.coffee(\.erb)?$/,
  use: [{
    loader: 'coffee-loader',
    options: {
      transpile: {} // it seems that transpile options can be used here,
                    // but I couldn't find what to use
    }
  }]
}

Update

Instead of configuring coffee to transpile (as mentioned before), in this issue it does recommend configuring babel loader to not ignore coffee files (it does not process coffee files on the default config)

// config/webpack/environment.js

// Make babel process coffee files
environment.loaders.get('babel').test = /\.(js|jsx|mjs|ts|tsx|coffee)?(\.erb)?$/

After that it does work.



来源:https://stackoverflow.com/questions/61615873/how-to-use-react-within-rails-using-coffee

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!