sinatra - 如何在Sinatra中使用coffeescript

标签 sinatra coffeescript

我正在尝试与Sinatra合作使用coffeescript。我对这两种技术都是新手,所以这可能很愚蠢。我的问题似乎是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>

最佳答案

嗯...看来您的示例基于this Sinatra documentation。但是由于某些原因,Sinatra试图将.js文件提供为HTML,并相应地对其进行了预处理。您是否有机会在应用程序的其他位置设置content_type?尝试将代码更改为

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

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

编辑:发布上述内容后,令我惊讶的是,我可能只是误解了您的标记。当您在浏览器中加载页面test.js时看到的就是
alert('hello world!');

?如果是这样,则一切正常。只有在<script>标记之间的HTML页面中或通过<script src="test.js"></script>引用的JavaScript页面中时,JavaScript才会在浏览器中运行。因此,除了您现有的代码外,
get "/alert", :provides => 'html' do
  '<script type=src="test.js"></script>'
end

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

关于sinatra - 如何在Sinatra中使用coffeescript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5660964/

相关文章:

ruby-on-rails - Heroku 的 Facebook Canvas 应用教程 : oath error

ruby - 如何在 Sinatra 中创建类似 Rails 的前置过滤器?

javascript - 包含 Assets javascript Coffee 以查看 Rails 上的部分内容

jquery - 点击后添加CSS类

javascript - 配置从 node_modules 读取的 requirejs

javascript - 不允许的参数 : songs_attributes

node.js - 如何在 VSCode 中调试 CoffeeScript?

ruby - 模拟文件输入作为 Rspec 上的文件路径

ruby - 在使用 erubis 的 sinatra 中,默认设置 escape_html 为真。有时不得不逃避

ruby - Sinatra 路由中定义的全局变量是否在请求之间共享?