如何在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>
    
已邀请:
嗯...看来您的示例基于此Sinatra文档。但是由于某种原因,Sinatra试图将
.js
文件作为HTML提供,并相应地对其进行了预处理。您是否有可能在应用程序的其他位置设置
content_type
?尝试将代码更改为
get \"/test.js\" do
  content_type \"text/javascript\"
  coffee :hello
end
您还可以尝试使用一种完全不同的方法,使用Rack :: Coffee或Barista在Rack级别自动将CoffeeScript编译为JavaScript。如果您仍然有大量的CoffeeScript文件,那可能会更容易。 编辑:发布以上内容后,令我震惊的是,我可能只是误解了您的标记。在浏览器中加载页面
test.js
时看到的就是
alert(\'hello world!\');
?如果是这样,则一切正常。仅当JavaScript代码位于
<script>
标记之间或通过
<script src=\"test.js\"></script>
引用的HTML页面中时,它才会在浏览器中运行。因此,除了您现有的代码外,
get \"/alert\", :provides => \'html\' do
  \'<script type=src=\"test.js\"></script>\'
end
然后在浏览器中打开该“ 9”地址,脚本应运行。     
从sinatra咖啡脚本模板 我只是在寻找相同的设置。
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\'
索引
<h1>I\'m living the dream</h1>
<button>Click me</button>
布局
<!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>
    
我通常在开发
coffee -wc dirname/
时在我的CoffeeScript文件上设置观察程序,然后将编译后的JS文件部署到生产环境中。它不是理想的,但是在某些方面却不太复杂,并且从生产服务器(在我的情况下为Heroku)中删除了对Node.JS的依赖。     
使用像sinatra-asset-snack(https://rubygems.org/gems/sinatra-asset-snack)之类的宝石,甚至更好,使用引导程序启动您的项目,这样您就不必担心设置所有项目管道(https://github.com/benkitzelman/sinatra-backbone-bootstrap)     

要回复问题请先登录注册