如何使用咖啡在 Rails 内使用 React?

How to use React within Rails using coffee?

我正在 Rails 应用程序 (5.2) 上添加 Reactjs,但我想使用 coffeescript 来编写它。我添加了 webpack 并安装了 react 和 coffee 支持,两者似乎都有效,但是当我想同时使用它们时,我得到:

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>;
| });
|

我还更新了 coffeescript 到 2.0 版本,应该原生支持 jsx。我可能缺少什么?

我终于让它工作了,问题是(正如@caffeinated.tech提到的)配置相当棘手。

使其在以下位置运行所需的步骤:

  • 将 coffeescript 版本 2 添加到依赖项中(默认情况下 webpacker 安装版本 1)。

  • 确保 coffeescript 加载程序附加到加载程序(它是 prepended by default):

// config/webpack/environment.js

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

// instead of environment.loaders.prepend('coffee', coffee)
environment.loaders.append('coffee', coffee)
/// ...
// 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
    }
  }]
}

更新

this issue it does recommend configuring babel loader to not ignore coffee files (it does not process coffee files on the default config)

中,而不是将 coffee 配置为转译(如前所述)
// config/webpack/environment.js

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

之后它确实起作用了。