在JavaScript中,必须最小化文件时省略分号是否安全? [英] In JavaScript, is it safe to omit semicolons when file have to be minifyed?

查看:102
本文介绍了在JavaScript中,必须最小化文件时省略分号是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几个星期以来,我在JavaScript文件中省略了分号.我今天意识到,如果文件缩小了,可能会引起问题.

Since a few week, I omit semicolons in my JavaScript files. I realized today it may cause issues if the file is minifyed.

我阅读了以下资源:

  • https://www.reddit.com/r/javascript/comments/3ykv0w/is_it_actually_true_that_minifiers_break_js_code/
  • https://github.com/mrclay/minify/issues/396
  • https://github.com/github/fetch/issues/420

有两种观点:

  • 如果某个工具处理了有效的javascript文件并将其转换为无效的javascript文件,则该工具将无法实现其不更改其功能"的承诺.
  • 由于省略分号会阻止文件缩小,因此必须添加分号.

一般情况下最好的选择是什么?我的意思是一般情况",即源代码应该是通用的,并应由任何压缩程序最小化.

What is the best option in the general case? I mean by "general case" that the source code should be generic and minifyed by any minifyer.

推荐答案

只要缩小器中没有bug,就不会引起问题.

It shouldn't cause problems, as long as the minifier does not have bugs within it.

这是因为不带分号的JavaScript代码是完全有效且可解析的JavaScript.

This is because JavaScript code without semicolons is perfectly valid, parseable JavaScript.

这可以准确且可重复地最小化.

And this can be accurately and reproducibly minified.

不涉及猜测"-仅基于

No "guesswork" will be involved - only a well-defined, deterministic parsing algorithm, based on the specification.

以前在与ASI有关的缩小器中发现了臭虫.

Bugs have previously been identified in minifiers related to ASI.

因此,根据矿工的成熟程度,击中此类bug的风险可能会增加.

So depending on the maturity of the minifier, there might be an increased risk of hitting such a bug.

也就是说,以前在与ASI不相关的缩小器中也发现了错误,因此,无论使用或不使用分号,缩小器始终存在引入问题的风险.

That said, bugs have previously been found in minifiers unrelated to ASI too, so there will always be a risk that your minifier introduces a problem, regardless of whether you use semicolons or not.

鉴于所有这些以及JavaScript压缩工具的高品质和成熟度,我将遵循使您的团队最快乐的编码风格.

这篇关于在JavaScript中,必须最小化文件时省略分号是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆