Is it possible to compile Coffeescript code in script tags in html files? [duplicate]

可紊 提交于 2020-01-01 04:57:05

问题


Possible Duplicate:
Is there a way to send CoffeeScript to the client's browser and have it compiled to JavaScript there?

Is there a simple way to compile Coffeescript that is inside <script> tags inside html, or do you usually have all Coffeescript in separate files?


回答1:


Responding to dvcolgan's clarifying comment:

So, you want to have an HTML file on the server with inline CoffeeScript that gets served as HTML with inline JavaScript. The CoffeeScript compiler doesn't support this directly, but you could write a Node script to do it fairly easily, using the coffee-script library and jsdom to do the HTML parsing.

Exactly how you want to implement this would depend on the web framework you're using. You probably don't want the CoffeeScript compiler to run on every request (it's pretty fast, but it's still going to reduce the number of requests/second your server can handle); instead, you'd want to compile your HTML once and then serve the compiled version from a cache. Again, I don't know of any existing tools that do this, but it shouldn't be too hard to write your own.




回答2:


Indeed there is. There's a post about it here.

The summary of that article is this:

  1. Include in your HTML document your script with type text/coffeescript
  2. Include in the head of the page this line:

    <script type="text/javascript" src="https://raw.githubusercontent.com/jashkenas/coffeescript/master/lib/coffee-script/coffee-script.js"></script>
    

Beware that doing this isn't encouraged.

<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>


来源:https://stackoverflow.com/questions/7860942/is-it-possible-to-compile-coffeescript-code-in-script-tags-in-html-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!