如何在Rails资产Pipeleine中共享不同coffeescript文件中的代码

How to share code in different coffeescript files in Rails Asset Pipeleine

本文关键字:coffeescript 文件 代码 共享 Rails 资产 Pipeleine      更新时间:2023-09-26

我共享了.js.coffee

Shared =
  shared_method: (msg) ->
    alert(msg)

我有test.js.coffee

Shared.shared_method("this doesn't work")

我首先在application.js中加载共享代码,如下所述https://stackoverflow.com/a/20563242/656510

 //= require ./shared 
 //= require_tree .

然而,它在开发中不起作用,我得到:Uncaught ReferenceError:Shared没有定义

当我看到JS时,它被作为单独的文件提供,而不是像在生产中那样被编译到application.JS中。

正如我所想的那样,我创建了一个干净的Rails4.1应用程序来演示这个问题。

https://github.com/itinsley/asset_pipeline_weirdness

非常感谢您的帮助。

您需要使用全局名称空间:

 @Shared =
  shared_method: (msg) ->
    alert(msg)

如果你愿意,你可以为你的应用程序使用一个名称空间:

 @myApp ||= {}
 myApp.Shared =
  shared_method: (msg) ->
    alert(msg)