我正在尝试与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::Coffee或Barista在机架级别将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/