Skip to content

Commit

Permalink
fix #1809: add the "--drop:debugger" flag
Browse files Browse the repository at this point in the history
  • Loading branch information
evanw committed Dec 29, 2021
1 parent 8302d94 commit ce7262f
Show file tree
Hide file tree
Showing 10 changed files with 57 additions and 1 deletion.
6 changes: 6 additions & 0 deletions CHANGELOG.md
@@ -1,5 +1,11 @@
# Changelog

## Unreleased

* Add the `--drop:debugger` flag ([#1809](https://github.com/evanw/esbuild/issues/1809))

Passing this flag causes all [`debugger;` statements](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/debugger) to be removed from the output. This is similar to the `drop_debugger: true` flag available in the popular UglifyJS and Terser JavaScript minifiers.

## 0.14.9

* Implement cross-module tree shaking of TypeScript enum values ([#128](https://github.com/evanw/esbuild/issues/128))
Expand Down
1 change: 1 addition & 0 deletions cmd/esbuild/main.go
Expand Up @@ -67,6 +67,7 @@ var helpText = func(colors logger.Colors) string {
--chunk-names=... Path template to use for code splitting chunks
(default "[name]-[hash]")
--color=... Force use of color terminal escapes (true | false)
--drop:... Remove certain constructs (debugger)
--entry-names=... Path template to use for entry point output paths
(default "[dir]/[name]", can also use "[hash]")
--footer:T=... Text to be appended to each output file of type T
Expand Down
1 change: 1 addition & 0 deletions internal/config/config.go
Expand Up @@ -221,6 +221,7 @@ type Options struct {
KeepNames bool
IgnoreDCEAnnotations bool
TreeShaking bool
DropDebugger bool

Defines *ProcessedDefines
TS TSOptions
Expand Down
9 changes: 8 additions & 1 deletion internal/js_parser/js_parser.go
Expand Up @@ -371,6 +371,7 @@ type optionsThatSupportStructuralEquality struct {
omitRuntimeForTests bool
ignoreDCEAnnotations bool
treeShaking bool
dropDebugger bool
unusedImportsTS config.UnusedImportsTS
useDefineForClassFields config.MaybeBool
}
Expand All @@ -397,6 +398,7 @@ func OptionsFromConfig(options *config.Options) Options {
omitRuntimeForTests: options.OmitRuntimeForTests,
ignoreDCEAnnotations: options.IgnoreDCEAnnotations,
treeShaking: options.TreeShaking,
dropDebugger: options.DropDebugger,
unusedImportsTS: options.UnusedImportsTS,
useDefineForClassFields: options.UseDefineForClassFields,
},
Expand Down Expand Up @@ -8904,9 +8906,14 @@ func (p *parser) keepStmtSymbolName(loc logger.Loc, ref js_ast.Ref, name string)

func (p *parser) visitAndAppendStmt(stmts []js_ast.Stmt, stmt js_ast.Stmt) []js_ast.Stmt {
switch s := stmt.Data.(type) {
case *js_ast.SDebugger, *js_ast.SEmpty, *js_ast.SComment:
case *js_ast.SEmpty, *js_ast.SComment:
// These don't contain anything to traverse

case *js_ast.SDebugger:
if p.options.dropDebugger {
return stmts
}

case *js_ast.STypeScript:
// Erase TypeScript constructs from the output completely
return stmts
Expand Down
2 changes: 2 additions & 0 deletions lib/shared/common.ts
Expand Up @@ -107,6 +107,7 @@ function pushCommonFlags(flags: string[], options: CommonOptions, keys: OptionKe
let minifySyntax = getFlag(options, keys, 'minifySyntax', mustBeBoolean);
let minifyWhitespace = getFlag(options, keys, 'minifyWhitespace', mustBeBoolean);
let minifyIdentifiers = getFlag(options, keys, 'minifyIdentifiers', mustBeBoolean);
let drop = getFlag(options, keys, 'drop', mustBeArray);
let charset = getFlag(options, keys, 'charset', mustBeString);
let treeShaking = getFlag(options, keys, 'treeShaking', mustBeBoolean);
let ignoreAnnotations = getFlag(options, keys, 'ignoreAnnotations', mustBeBoolean);
Expand Down Expand Up @@ -134,6 +135,7 @@ function pushCommonFlags(flags: string[], options: CommonOptions, keys: OptionKe
if (charset) flags.push(`--charset=${charset}`);
if (treeShaking !== void 0) flags.push(`--tree-shaking=${treeShaking}`);
if (ignoreAnnotations) flags.push(`--ignore-annotations`);
if (drop) for (let what of drop) flags.push(`--drop:${what}`);

if (jsx) flags.push(`--jsx=${jsx}`);
if (jsxFactory) flags.push(`--jsx-factory=${jsxFactory}`);
Expand Down
2 changes: 2 additions & 0 deletions lib/shared/types.ts
Expand Up @@ -3,6 +3,7 @@ export type Format = 'iife' | 'cjs' | 'esm';
export type Loader = 'js' | 'jsx' | 'ts' | 'tsx' | 'css' | 'json' | 'text' | 'base64' | 'file' | 'dataurl' | 'binary' | 'default';
export type LogLevel = 'verbose' | 'debug' | 'info' | 'warning' | 'error' | 'silent';
export type Charset = 'ascii' | 'utf8';
export type Drop = 'debugger';

interface CommonOptions {
/** Documentation: https://esbuild.github.io/api/#sourcemap */
Expand All @@ -21,6 +22,7 @@ interface CommonOptions {
/** Documentation: https://esbuild.github.io/api/#target */
target?: string | string[];

drop?: Drop[];
/** Documentation: https://esbuild.github.io/api/#minify */
minify?: boolean;
/** Documentation: https://esbuild.github.io/api/#minify */
Expand Down
8 changes: 8 additions & 0 deletions pkg/api/api.go
Expand Up @@ -239,6 +239,12 @@ const (
TreeShakingTrue
)

type Drop uint8

const (
DropDebugger Drop = 1 << iota
)

////////////////////////////////////////////////////////////////////////////////
// Build API

Expand All @@ -254,6 +260,7 @@ type BuildOptions struct {
Target Target // Documentation: https://esbuild.github.io/api/#target
Engines []Engine // Documentation: https://esbuild.github.io/api/#target

Drop Drop
MinifyWhitespace bool // Documentation: https://esbuild.github.io/api/#minify
MinifyIdentifiers bool // Documentation: https://esbuild.github.io/api/#minify
MinifySyntax bool // Documentation: https://esbuild.github.io/api/#minify
Expand Down Expand Up @@ -365,6 +372,7 @@ type TransformOptions struct {
Format Format // Documentation: https://esbuild.github.io/api/#format
GlobalName string // Documentation: https://esbuild.github.io/api/#global-name

Drop Drop
MinifyWhitespace bool // Documentation: https://esbuild.github.io/api/#minify
MinifyIdentifiers bool // Documentation: https://esbuild.github.io/api/#minify
MinifySyntax bool // Documentation: https://esbuild.github.io/api/#minify
Expand Down
2 changes: 2 additions & 0 deletions pkg/api/api_impl.go
Expand Up @@ -848,6 +848,7 @@ func rebuildImpl(
MangleSyntax: buildOpts.MinifySyntax,
RemoveWhitespace: buildOpts.MinifyWhitespace,
MinifyIdentifiers: buildOpts.MinifyIdentifiers,
DropDebugger: (buildOpts.Drop & DropDebugger) != 0,
AllowOverwrite: buildOpts.AllowOverwrite,
ASCIIOnly: validateASCIIOnly(buildOpts.Charset),
IgnoreDCEAnnotations: buildOpts.IgnoreAnnotations,
Expand Down Expand Up @@ -1339,6 +1340,7 @@ func transformImpl(input string, transformOpts TransformOptions) TransformResult
MangleSyntax: transformOpts.MinifySyntax,
RemoveWhitespace: transformOpts.MinifyWhitespace,
MinifyIdentifiers: transformOpts.MinifyIdentifiers,
DropDebugger: (transformOpts.Drop & DropDebugger) != 0,
ASCIIOnly: validateASCIIOnly(transformOpts.Charset),
IgnoreDCEAnnotations: transformOpts.IgnoreAnnotations,
TreeShaking: validateTreeShaking(transformOpts.TreeShaking, false /* bundle */, transformOpts.Format),
Expand Down
17 changes: 17 additions & 0 deletions pkg/cli/cli_impl.go
Expand Up @@ -96,6 +96,22 @@ func parseOptionsImpl(
transformOpts.MinifyIdentifiers = true
}

case strings.HasPrefix(arg, "--drop:"):
value := arg[len("--drop:"):]
switch value {
case "debugger":
if buildOpts != nil {
buildOpts.Drop |= api.DropDebugger
} else {
transformOpts.Drop |= api.DropDebugger
}
default:
return cli_helpers.MakeErrorWithNote(
fmt.Sprintf("Invalid value %q in %q", value, arg),
"Valid values are \"debugger\".",
), nil
}

case strings.HasPrefix(arg, "--legal-comments="):
value := arg[len("--legal-comments="):]
var legalComments api.LegalComments
Expand Down Expand Up @@ -638,6 +654,7 @@ func parseOptionsImpl(
colon := map[string]bool{
"banner": true,
"define": true,
"drop": true,
"external": true,
"footer": true,
"inject": true,
Expand Down
10 changes: 10 additions & 0 deletions scripts/js-api-tests.js
Expand Up @@ -3692,6 +3692,16 @@ let transformTests = {
assert.strictEqual(code, `console.log("ab"+c);\n`)
},

async keepDebugger({ esbuild }) {
const { code } = await esbuild.transform(`if (x) debugger`, { drop: [] })
assert.strictEqual(code, `if (x)\n debugger;\n`)
},

async dropDebugger({ esbuild }) {
const { code } = await esbuild.transform(`if (x) debugger`, { drop: ['debugger'] })
assert.strictEqual(code, `if (x)\n ;\n`)
},

async define({ esbuild }) {
const define = { 'process.env.NODE_ENV': '"production"' }
const { code } = await esbuild.transform(`console.log(process.env.NODE_ENV)`, { define })
Expand Down

0 comments on commit ce7262f

Please sign in to comment.