可能重複:
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