Discard comments in your CSS files with PostCSS.
npx @tessl/cli install tessl/npm-postcss-discard-comments@7.0.00
# PostCSS Discard Comments
1
2
PostCSS Discard Comments is a sophisticated PostCSS plugin that removes comments from CSS files with granular control. It offers options to preserve important comments (marked with `/*!`), remove all comments including important ones, or use custom removal logic through a callback function. The plugin efficiently processes CSS syntax including selectors, declarations, at-rules, and their raw spacing while maintaining proper formatting.
3
4
## Package Information
5
6
- **Package Name**: postcss-discard-comments
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install postcss-discard-comments`
10
- **Peer Dependencies**: Requires PostCSS ^8.4.32
11
12
## Core Imports
13
14
```javascript
15
const postcssDiscardComments = require("postcss-discard-comments");
16
```
17
18
For ES modules:
19
20
```javascript
21
import postcssDiscardComments from "postcss-discard-comments";
22
```
23
24
## Basic Usage
25
26
```javascript
27
const postcss = require("postcss");
28
const discardComments = require("postcss-discard-comments");
29
30
// Basic usage - removes regular comments, preserves /*! important */ comments
31
const result = await postcss([discardComments()])
32
.process('h1/* heading */{margin: 0 auto}/*! important */', { from: undefined });
33
34
console.log(result.css);
35
// Output: h1 {margin: 0 auto}/*! important */
36
```
37
38
## Architecture
39
40
PostCSS Discard Comments is built around several key components:
41
42
- **Plugin Creator**: Main function that returns a PostCSS plugin instance configured with the provided options
43
- **Comment Remover**: Internal class that implements the logic for determining which comments should be removed based on configuration
44
- **Comment Parser**: Internal utility that tokenizes CSS text to identify comment boundaries and content
45
- **Multi-Context Processing**: Processes comments across different CSS contexts including top-level comments, selector comments (using `postcss-selector-parser`), declaration values, at-rule parameters, and raw spacing
46
- **Performance Optimization**: Uses caching mechanisms (`matcherCache`, `replacerCache`) to avoid reprocessing identical patterns
47
48
The plugin operates during PostCSS's `OnceExit` phase, walking the entire CSS AST and applying comment removal logic to each node type while preserving proper formatting.
49
50
## Capabilities
51
52
### Plugin Creator Function
53
54
The main export is a plugin creator function that returns a PostCSS plugin instance configured with the provided options.
55
56
```javascript { .api }
57
/**
58
* Creates a PostCSS plugin for removing comments from CSS
59
* @param {Options} opts - Configuration options for comment removal
60
* @returns {Plugin} PostCSS plugin instance with postcssPlugin: 'postcss-discard-comments'
61
*/
62
function postcssDiscardComments(opts = {}): Plugin;
63
```
64
65
**Usage Examples:**
66
67
```javascript
68
// Default behavior - preserve important comments
69
const plugin1 = postcssDiscardComments();
70
71
// Remove all comments including important ones
72
const plugin2 = postcssDiscardComments({ removeAll: true });
73
74
// Keep only the first important comment
75
const plugin3 = postcssDiscardComments({ removeAllButFirst: true });
76
77
// Custom removal logic
78
const plugin4 = postcssDiscardComments({
79
remove: function(comment) {
80
return comment.startsWith('@'); // Remove comments starting with @
81
}
82
});
83
```
84
85
### Comment Removal Options
86
87
The plugin accepts an options object to control comment removal behavior.
88
89
```javascript { .api }
90
/**
91
* Configuration options for comment removal
92
* @typedef {Object} Options
93
* @property {boolean} [removeAll] - Remove all comments including important ones
94
* @property {boolean} [removeAllButFirst] - Remove all important comments except the first
95
* @property {function} [remove] - Custom function to determine comment removal
96
*/
97
interface Options {
98
/** Remove all comments including important ones marked with /*! */
99
removeAll?: boolean;
100
/** Remove all important comments except the first one encountered */
101
removeAllButFirst?: boolean;
102
/** Custom function to determine if a comment should be removed
103
* @param comment - Comment text without /* and */ delimiters
104
* @returns true to remove the comment, false to keep it
105
*/
106
remove?: (comment: string) => boolean;
107
}
108
```
109
110
**Option Details:**
111
112
- **removeAll**: When `true`, removes all comments including those marked as important with `/*!`
113
- **removeAllButFirst**: When `true`, preserves only the first important comment encountered and removes all others
114
- **remove**: Custom function that receives the comment text (without `/*` and `*/`) and returns a boolean. If provided, other options are ignored.
115
116
**Usage Examples:**
117
118
```javascript
119
// Remove all comments
120
const css1 = '/*! license */h1/* heading */{margin: 0}';
121
const result1 = postcss([discardComments({ removeAll: true })])
122
.process(css1, { from: undefined });
123
// Output: h1{margin: 0}
124
125
// Keep only first important comment
126
const css2 = '/*! license */h1{margin: 0}/*! author */';
127
const result2 = postcss([discardComments({ removeAllButFirst: true })])
128
.process(css2, { from: undefined });
129
// Output: /*! license */h1{margin: 0}
130
131
// Custom removal logic
132
const css3 = '/*@ remove this */h1/* keep this */{margin: 0}';
133
const result3 = postcss([discardComments({
134
remove: function(comment) { return comment.startsWith('@'); }
135
})])
136
.process(css3, { from: undefined });
137
// Output: h1/* keep this */{margin: 0}
138
```
139
140
### Plugin Properties
141
142
The plugin function includes a static property for PostCSS compatibility.
143
144
```javascript { .api }
145
/** PostCSS plugin marker property */
146
postcssDiscardComments.postcss = true;
147
```
148
149
## Processing Behavior
150
151
The plugin processes CSS comments in various contexts:
152
153
- **Top-level comments**: Direct comment nodes in the CSS AST
154
- **Selector comments**: Comments within CSS selectors using `postcss-selector-parser`
155
- **Declaration comments**: Comments in property values and `!important` declarations
156
- **At-rule comments**: Comments in at-rule parameters and spacing
157
- **Raw spacing**: Comments in the raw spacing between CSS nodes
158
159
The plugin uses caching mechanisms (`matcherCache`, `replacerCache`) for performance optimization when processing repeated patterns.
160
161
## Integration
162
163
This plugin is designed for use in CSS build pipelines and optimization workflows. It integrates seamlessly with other PostCSS plugins and is commonly used in production builds where comment removal is desired to reduce file size while preserving critical license or attribution comments when needed.
164
165
```javascript
166
// Example build configuration
167
const postcss = require("postcss");
168
const discardComments = require("postcss-discard-comments");
169
const cssnano = require("cssnano");
170
171
const processor = postcss([
172
discardComments({ removeAllButFirst: true }), // Keep first license comment
173
cssnano() // Further optimization
174
]);
175
```