可能重复:
Is there a way to send CoffeeScript to the client's browser and have it compiled to JavaScript there?是否可以在html文件的脚本标记中编译Coffeescript代码?
有没有一种简单的方法来编译CoffeeScript的是内里的html <script>
标签,或者你平常都在的CoffeeScript单独的文件?
可能重复:
Is there a way to send CoffeeScript to the client's browser and have it compiled to JavaScript there?是否可以在html文件的脚本标记中编译Coffeescript代码?
有没有一种简单的方法来编译CoffeeScript的是内里的html <script>
标签,或者你平常都在的CoffeeScript单独的文件?
应对dvcolgan澄清真实的评论:
所以,你想拥有与被充当HTML与内嵌的JavaScript内嵌的CoffeeScript在服务器上的HTML文件。 CoffeeScript编译器不直接支持这一点,但是您可以使用coffee-script
库和jsdom来编写Node脚本来轻松完成HTML解析。
具体如何实现这一点取决于您使用的Web框架。您可能不希望CoffeeScript编译器在每个请求上运行(它非常快,但它仍然会减少服务器可以处理的请求数/秒)。相反,您需要编译一次HTML,然后从缓存中提供编译后的版本。再次,我不知道任何现有的工具可以做到这一点,但编写自己的应用程序不应该太难。
确实有。有一个关于它的帖子here。
该文章的总结是这样的:
text/coffeescript
在页面头部包含此行:
<script type="text/javascript" src="https://raw.githubusercontent.com/jashkenas/coffeescript/master/lib/coffee-script/coffee-script.js"></script>
请注意不要这样做。
<html>
<head>
<title>In-Browser test</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript">
</script>
<script src="https://raw.githubusercontent.com/jashkenas/coffeescript/master/lib/coffee-script/coffee-script.js" type="text/javascript">
</script>
</head>
<body>
<script type="text/coffeescript">
$ -> $('#header').css 'background-color', 'green'
</script>
<h1 style="color:white" id="header">CoffeeScript is alive!</h1>
</body>
</html>
代码段在Chrome中失败:拒绝执行'http://github.com/jashkenas/coffee-script/raw/master/extras/coffee-script.js'脚本,因为它的MIME类型('text/plain')不可执行,并且启用严格的MIME类型检查。 –
安德鲁已经钉了它。另见:http://stackoverflow.com/questions/5170473/is-there-a-way-to-send-coffeescript-to-the-clients-browser-and-have-it-compiled –
我更想到在服务器上将内联Coffeescript编译为Javascript。基本上运行Coffeescript编译器作为预处理器并忽略HTML。 – davidscolgan
为什么你不能把它放在一个单独的文件中的任何具体原因?这样你可以使用现有的工具链。否则,你不得不在他的回答中推出类似@Trevor的提及。 – Thilo