Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
131 views
in Technique[技术] by (71.8m points)

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

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

<script type="text/coffeescript">
    square = (x) -> x * x
    list = [1, 2, 3, 4, 5]        
    squares = (square num for num in list)
</script>

The CoffeeScript compiler is written in JavaScript, so can I send it to the client to compile/run this code in the client's browser?

question from:https://stackoverflow.com/questions/5170473/is-there-a-way-to-send-coffeescript-to-the-clients-browser-and-have-it-compiled

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Jeremy already has this one, but let me add some important details and caveats:

  1. At 39k gzipped (compare to jQuery at 29k), coffee-script.js is a big file; so unless you're actually letting your users run their own CoffeeScript, you really shouldn't use it in production.
  2. As mentioned in the documentation, each CoffeeScript snippet will be in its own anonymous closure. So your example snippet wouldn't do anything—squares wouldn't be visible outside of the script. Instead, you'd want to change it to window.squares = ....
  3. All CoffeeScript code, whether external or inline, will run after all JavaScript code on the page. That's because coffee-script.js doesn't read your <script type="text/coffeescript> tags until after the document is ready, by which time your JavaScripts have already run.
  4. Remote CoffeeScripts are loaded via XMLHTTPRequest, which means that they must be hosted on the same domain as your site. (Certain browsers—Chrome, at least—also have a problem with doing XMLHTTPRequests on file:// paths.)
  5. Currently, the order in which different remote CoffeeScripts run is not guaranteed. I submitted a patch for this, but it's not officially a part of CoffeeScript yet. See this pull request.

So, you might want to look at some alternatives for serving CoffeeScript as compiled JavaScript instead. If you're developing for a Ruby or Python server, there are plugins available. I've tried to list them all at http://github.com/jashkenas/coffee-script/wiki/Web-framework-plugins.

If you're developing a site without a backend, a tool I highly recommend looking at is Middleman, which lets you work with CoffeeScript (as well as Haml and Sass, if you want) during development, then compile and minify it for production deployment.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...