Remove Code Comments — Strip Comments from JS, CSS, and HTML
Learn how comment removal works across JavaScript, CSS, and HTML. Understand which comments are safe to remove, how to preserve license comments, and the impact on file size.
Detailed Explanation
Removing Comments from Code
Comment removal is one of the simplest and most effective minification steps. Comments exist only for developer readability and have zero runtime impact, so they can be safely stripped from production builds.
JavaScript Comments
JavaScript has two comment syntaxes:
// Single-line comment
/*
* Multi-line
* comment block
*/
/** JSDoc documentation comment */
All three are removed during minification. The tricky part is distinguishing comments from similar-looking syntax:
- Regular expressions:
/pattern/gis not a comment, even though it starts with/. - URLs in strings:
"https://example.com"contains//but is not a comment. - Template literals: Backtick strings may contain
//or/*that should be preserved.
A proper comment remover uses a parser (not regex) to correctly handle these cases.
CSS Comments
CSS uses only multi-line comments:
/* This is a CSS comment */
/*!
* This is a license comment — note the exclamation mark.
* Many minifiers preserve these by default.
*/
The /*! */ convention signals that a comment should survive minification. This is important for open-source license compliance (e.g., MIT license headers).
HTML Comments
<!-- Standard HTML comment -->
<!--[if IE 9]>
<link rel="stylesheet" href="ie9.css">
<![endif]-->
Standard comments are removed, but conditional comments (for legacy IE support) may need to be preserved depending on your browser support requirements.
Preserving License Comments
Most build tools provide options to keep license comments:
- Terser:
comments: /^!/orcomments: "some"keeps comments with@licenseor!. - cssnano:
discardComments: { except: /^!/ }preserves/*! */comments. - webpack:
LicenseWebpackPluginextracts licenses to a separate file.
Size Impact
Comments often account for 10-30% of source file size, especially in well-documented codebases. JSDoc-heavy libraries can have more comment characters than actual code.
Use Case
Comment removal is essential for production deployments. Beyond reducing file size, stripping comments also removes potentially sensitive information — TODO notes, developer names, internal API references, and debugging hints that should not be exposed publicly.