问题
Since a few week, I omit semicolons in my JavaScript files. I realized today it may cause issues if the file is minifyed.
I read the following ressources:
- 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
There are two points of view:
- If a tool processes a javascript file that worked and turned it into a javascript file that doesn't work, that tool doesn't hold true to its promise of “without changing its functionality”.
- Since omiting semicolons prevent the file from being minifyed, semicolons must be added.
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.
回答1:
It shouldn't cause problems, as long as the minifier does not have bugs within it.
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.
Bugs have previously been identified in minifiers related to ASI.
So depending on the maturity of the minifier, there might be an increased risk of hitting such a bug.
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.
Given all this, and the high quality and maturity of JavaScript minifiers, I would follow the coding style that makes your team happiest.
来源:https://stackoverflow.com/questions/59793770/in-javascript-is-it-safe-to-omit-semicolons-when-file-have-to-be-minifyed