如何在Sinatra中使用coffeescript

Jac*_*lla 8 sinatra coffeescript

我正在努力让coffeescript与Sinatra合作.我对这两种技术都不熟悉,所以这可能是愚蠢的.我的问题似乎是coffeescript编译为javascript但不在页面上执行,而是显示为html.

#sinatra app
require 'coffee-script'
get "/test.js" do
  coffee :hello
end

#hello.coffee
alert "hello world"

#My page (/test.js) doesn't execute the js - just displays the code

#On screen in the browser I get this:
   (function() {
  alert("hello world");
}).call(this);

#In the HTML I get this within the body tags

<pre style="word-wrap: break-word; white-space: pre-wrap;">(function() {
  alert('hello world!');
}).call(this);
</pre>
Run Code Online (Sandbox Code Playgroud)

Tre*_*ham 6

嗯......看起来你的例子是基于这个Sinatra文档.但由于某种原因,Sinatra试图将该.js文件作为HTML提供,并相应地对其进行预处理.您是否有机会content_type在您的应用程序中设置其他地方?尝试将代码更改为

get "/test.js" do
  content_type "text/javascript"
  coffee :hello
end
Run Code Online (Sandbox Code Playgroud)

您还可以尝试使用完全不同的方法,使用Rack :: CoffeeBarista在Rack级别自动将CoffeeScript编译为JavaScript.如果你有大量的CoffeeScript文件,这可能会更容易.

编辑:发布上述内容后,让我感到震惊的是我可能只是误解了你的标记.是您test.js在浏览器中加载页面时看到的内容

alert('hello world!');
Run Code Online (Sandbox Code Playgroud)

?如果是这样,一切都很好.只有在<script>标记之间的HTML页面中或通过引用时,JavaScript才会在浏览器中运行<script src="test.js"></script>.所以除了你现有的代码,添加

get "/alert", :provides => 'html' do
  '<script type=src="test.js"></script>'
end
Run Code Online (Sandbox Code Playgroud)

然后alert在浏览器中打开该地址,脚本应该运行.