0
# Parcel Terser Optimizer
1
2
A Parcel optimizer plugin that uses Terser to minify JavaScript code for production builds. This plugin integrates with Parcel's optimization pipeline to compress and optimize JavaScript bundles with advanced minification techniques.
3
4
## Package Information
5
6
- **Package Name**: @parcel/optimizer-terser
7
- **Package Type**: npm
8
- **Language**: JavaScript (Flow typed)
9
- **Installation**: This is a Parcel plugin, typically included automatically in Parcel builds
10
11
## Core Imports
12
13
This package is designed as a Parcel plugin and is not directly imported by user code. Instead, it is automatically loaded by Parcel during the build process when JavaScript optimization is enabled.
14
15
For Parcel configuration:
16
17
```javascript
18
// .parcelrc
19
{
20
"optimizers": {
21
"*.js": ["@parcel/optimizer-terser"]
22
}
23
}
24
```
25
26
## Basic Usage
27
28
The plugin is used automatically by Parcel during production builds. It can be configured through standard Terser configuration files:
29
30
```javascript
31
// .terserrc.js
32
module.exports = {
33
compress: {
34
drop_console: true,
35
drop_debugger: true
36
},
37
mangle: {
38
toplevel: true
39
},
40
format: {
41
comments: false
42
}
43
};
44
```
45
46
## Architecture
47
48
The Parcel Terser Optimizer is built on Parcel's plugin architecture:
49
50
- **Plugin System**: Extends Parcel's `Optimizer` base class from `@parcel/plugin`
51
- **Configuration Loading**: Automatically discovers and loads Terser configuration files
52
- **Bundle Processing**: Integrates with Parcel's bundle objects and file system
53
- **Error Handling**: Provides enhanced error reporting with source map integration
54
- **Source Map Support**: Preserves and transforms source maps during minification
55
56
## Capabilities
57
58
### Plugin Export
59
60
The main export is a configured Parcel Optimizer instance that handles JavaScript minification.
61
62
```javascript { .api }
63
/**
64
* Default export: Configured Parcel Optimizer instance
65
* Contains loadConfig and optimize methods for JavaScript minification
66
*/
67
declare const TerserOptimizer: Optimizer;
68
export default TerserOptimizer;
69
```
70
71
### Configuration Loading
72
73
Loads user configuration from standard Terser configuration files.
74
75
```javascript { .api }
76
/**
77
* Loads Terser configuration from project configuration files
78
* @param {Object} context - Parcel configuration context
79
* @param {Object} context.config - Parcel config loader
80
* @param {Object} context.options - Parcel build options
81
* @returns {Promise<Object|undefined>} User configuration or undefined
82
*/
83
async function loadConfig({ config, options });
84
```
85
86
**Supported configuration files:**
87
- `.terserrc` - JSON configuration
88
- `.terserrc.js` - JavaScript configuration (CommonJS)
89
- `.terserrc.cjs` - JavaScript configuration (CommonJS)
90
- `.terserrc.mjs` - JavaScript configuration (ES modules)
91
92
### Bundle Optimization
93
94
Performs JavaScript minification using Terser with comprehensive error handling.
95
96
```javascript { .api }
97
/**
98
* Optimizes JavaScript bundle contents using Terser
99
* @param {Object} context - Optimization context
100
* @param {Blob} context.contents - Bundle contents to optimize
101
* @param {SourceMap} context.map - Source map for the bundle
102
* @param {Bundle} context.bundle - Bundle metadata and configuration
103
* @param {Object} context.config - User configuration from loadConfig
104
* @param {Object} context.options - Parcel build options
105
* @param {Function} context.getSourceMapReference - Source map reference generator
106
* @returns {Promise<{contents: string, map: SourceMap}>} Optimized bundle
107
*/
108
async function optimize({
109
contents,
110
map,
111
bundle,
112
config,
113
options,
114
getSourceMapReference
115
});
116
```
117
118
## Configuration Options
119
120
The plugin accepts all standard Terser configuration options through configuration files:
121
122
### Compression Options
123
124
```javascript
125
{
126
compress: {
127
dead_code: true, // Remove unreachable code
128
drop_console: false, // Remove console statements
129
drop_debugger: true, // Remove debugger statements
130
keep_fargs: false, // Keep function arguments
131
passes: 1, // Number of compression passes
132
unsafe: false // Enable unsafe optimizations
133
}
134
}
135
```
136
137
### Mangling Options
138
139
```javascript
140
{
141
mangle: {
142
toplevel: false, // Mangle top-level names (auto-set based on output format)
143
properties: false, // Mangle property names
144
keep_fnames: false, // Keep function names
145
safari10: false // Safari 10 compatibility
146
}
147
}
148
```
149
150
### Output Format Options
151
152
```javascript
153
{
154
format: {
155
comments: false, // Preserve comments
156
beautify: false, // Beautify output
157
indent_level: 2, // Indentation level
158
semicolons: true, // Use semicolons
159
shorthand: true // Use shorthand properties
160
}
161
}
162
```
163
164
### Source Map Options
165
166
Source map options are automatically configured based on Parcel's environment settings:
167
168
```javascript
169
{
170
sourceMap: {
171
filename: "bundle.js", // Output filename (auto-generated)
172
asObject: true, // Return source map as object
173
content: "...", // Input source map content
174
}
175
}
176
```
177
178
## Environment Integration
179
180
The plugin integrates with Parcel's build environment:
181
182
### Build Conditions
183
184
```javascript { .api }
185
/**
186
* Environment conditions that affect optimization behavior
187
*/
188
interface BuildEnvironment {
189
/** Whether optimization should be performed (production builds) */
190
shouldOptimize: boolean;
191
/** Whether source maps should be generated */
192
sourceMap: boolean;
193
/** Output format for module-specific optimizations */
194
outputFormat: 'esmodule' | 'commonjs' | 'global';
195
}
196
```
197
198
### Optimization Features
199
200
- **Conditional Optimization**: Only runs in production builds (`bundle.env.shouldOptimize`)
201
- **Format-Specific Options**: Adjusts `toplevel` and `module` settings based on output format
202
- **Source Map Integration**: Preserves and transforms source maps when enabled
203
- **Error Recovery**: Provides detailed error reporting with code frames and hints
204
205
## Error Handling
206
207
The plugin provides comprehensive error handling with enhanced diagnostics:
208
209
### Error Types
210
211
```javascript { .api }
212
/**
213
* Enhanced error reporting for Terser optimization failures
214
*/
215
interface TerserError {
216
/** Error message from Terser */
217
message: string;
218
/** Line number in the processed code */
219
line?: number;
220
/** Column number in the processed code */
221
col?: number;
222
}
223
224
/**
225
* Diagnostic information for error reporting
226
*/
227
interface ErrorDiagnostic {
228
/** Human-readable error message */
229
message: string;
230
/** Plugin origin identifier */
231
origin: '@parcel/optimizer-terser';
232
/** Code frames showing error location */
233
codeFrames: CodeFrame[];
234
/** Helpful hints for resolving the error */
235
hints: string[];
236
}
237
```
238
239
### Error Features
240
241
- **Source Map Error Mapping**: Maps errors back to original source locations when possible
242
- **Code Frame Generation**: Shows relevant code context around errors
243
- **Helpful Hints**: Provides suggestions for common Terser compatibility issues
244
- **Dual Error Reporting**: Shows both original and transformed code locations in verbose mode
245
246
## Types
247
248
```javascript { .api }
249
/**
250
* Parcel Bundle object containing metadata and configuration
251
*/
252
interface Bundle {
253
/** Bundle name and file information */
254
name: string;
255
/** Target build configuration */
256
target: {
257
distDir: string;
258
};
259
/** Environment configuration */
260
env: {
261
shouldOptimize: boolean;
262
sourceMap: boolean;
263
outputFormat: 'esmodule' | 'commonjs' | 'global';
264
};
265
}
266
267
/**
268
* Parcel build options and configuration
269
*/
270
interface ParcelOptions {
271
/** Project root directory */
272
projectRoot: string;
273
/** File system abstraction */
274
inputFS: FileSystem;
275
/** Logging level configuration */
276
logLevel: 'none' | 'error' | 'warn' | 'info' | 'verbose';
277
}
278
279
/**
280
* Parcel file system abstraction
281
*/
282
interface FileSystem {
283
readFile(filePath: string, encoding: string): Promise<string>;
284
}
285
286
/**
287
* Parcel source map handling
288
*/
289
interface SourceMap {
290
stringify(options: object): Promise<string>;
291
addVLQMap(map: object): void;
292
}
293
294
/**
295
* Parcel Optimizer base class
296
*/
297
interface Optimizer {
298
loadConfig(context: {config: any, options: ParcelOptions}): Promise<any>;
299
optimize(context: OptimizeContext): Promise<OptimizationResult>;
300
}
301
302
/**
303
* Optimization context passed to optimize method
304
*/
305
interface OptimizeContext {
306
contents: Blob;
307
map: SourceMap | null;
308
bundle: Bundle;
309
config: any;
310
options: ParcelOptions;
311
getSourceMapReference: SourceMapReferenceGenerator;
312
}
313
314
/**
315
* Blob represents bundle contents
316
*/
317
interface Blob {
318
// Internal Parcel representation of file contents
319
}
320
321
/**
322
* Code frame for error reporting
323
*/
324
interface CodeFrame {
325
language: string;
326
filePath?: string;
327
code: string;
328
codeHighlights: Array<{
329
message: string;
330
start: {line: number, column: number};
331
end: {line: number, column: number};
332
}>;
333
}
334
335
/**
336
* Source map reference generator function
337
*/
338
interface SourceMapReferenceGenerator {
339
(sourceMap: SourceMap): Promise<string>;
340
}
341
342
/**
343
* Optimization result containing minified code and source map
344
*/
345
interface OptimizationResult {
346
/** Minified JavaScript code */
347
contents: string;
348
/** Transformed source map (if enabled) */
349
map: SourceMap | null;
350
}
351
```