9

I'm trying to get coffeescript working with Sinatra. I'm new to both technologies so this is probably something silly. My problem seems to be that the coffeescript compiles to javascript but doesn't execute on page, instead appearing as 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>
4

4 回答 4

6

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

get "/test.js" do
  content_type "text/javascript"
  coffee :hello
end

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

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

alert('hello world!');

? 如果是这样,一切正常。JavaScript 只有在<script>标签之间的 HTML 页面中或通过<script src="test.js"></script>. 所以除了你现有的代码,添加

get "/alert", :provides => 'html' do
  '<script type=src="test.js"></script>'
end

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

于 2011-04-14T15:19:00.173 回答
3

sinatra-coffee-script-template 我只是在寻找相同的设置。

require 'rubygems'
require 'bundler/setup'
require 'sinatra'
require 'coffee-script'

get '/' do
  erb :index
end

get '/application.js' do
  coffee :application
end

然后在 application.coffee

$(document).ready ->
  $('button:first').click ->
    $('body').toggleClass 'dark', 'light'

索引.erb

<h1>I'm living the dream</h1>
<button>Click me</button>

布局.erb

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>Sinatra Coffee-Script Template</title>
  <style type="text/css">
    .dark {
      background: #2F2F2F;
      color: #7F7F7F;
    }
    .light {
      background: #EEEEEE;
      color: #2F2F2F;
    }
  </style>
</head>
<body>
  <%= yield %>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
  <script src="/javascripts/listeners.js" type="text/javascript"></script>
</body>
</html>
于 2011-06-01T19:08:17.293 回答
2

我通常只是在开发时在我的 CoffeeScript 文件上设置一个观察coffee -wc dirname/程序,然后将编译后的 JS 文件部署到生产环境中。这并不理想,但它在某些方面不那么复杂,并且从我的生产服务器(在我的情况下是 Heroku)中删除了对 Node.JS 的依赖。

于 2011-04-15T11:10:00.787 回答
0

使用像 sinatra-asset-snack ( https://rubygems.org/gems/sinatra-asset-snack ) 这样的 gem,或者更好的是,使用引导程序启动您的项目,这样您就不必担心设置所有管道(https://github.com/benkitzelman/sinatra-backbone-bootstrap

于 2013-03-29T07:54:01.590 回答