是否可以在 html 文件的脚本标签中编译 Coffeescript 代码?

2022-01-24 00:00:00 html coffeescript

可能重复:
有吗一种将 CoffeeScript 发送到客户端浏览器并将其编译为 JavaScript 的方法那里?

有没有一种简单的方法来编译 html 中的 <script> 标签内的 Coffeescript,或者您通常将所有 Coffeescript 放在单独的文件中?

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?

推荐答案

回应dvcolgan的澄清评论:

Responding to dvcolgan's clarifying comment:

因此,您希望在服务器上有一个带有内联 CoffeeScript 的 HTML 文件,该文件作为带有内联 JavaScript 的 HTML 提供.CoffeeScript 编译器不直接支持这一点,但您可以编写一个 Node 脚本来相当容易地做到这一点,使用 coffee-script 库和 jsdom 进行 HTML 解析.

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.

具体实现方式取决于您使用的网络框架.您可能不希望 CoffeeScript 编译器在每个请求上都运行(它非常快,但它仍然会减少服务器可以处理的每秒请求数);相反,您希望编译一次 HTML,然后从缓存中提供编译后的版本.同样,我不知道有任何现有的工具可以做到这一点,但编写自己的工具应该不会太难.

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.

相关文章