Skip to content

Commit

Permalink
Provide a flag to auto-prefix local css classes when minified
Browse files Browse the repository at this point in the history
  • Loading branch information
chowey committed Oct 15, 2024
1 parent d34e79e commit 7c1e87c
Show file tree
Hide file tree
Showing 8 changed files with 33 additions and 2 deletions.
2 changes: 2 additions & 0 deletions cmd/esbuild/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,8 @@ var helpText = func(colors logger.Colors) string {
eof | linked | external, default eof when bundling
and inline otherwise)
--line-limit=... Lines longer than this will be wrap onto a new line
--local-css-prefix=... Add a prefix to local-css classes if
minify-identifiers is enabled
--log-level=... Disable logging (verbose | debug | info | warning |
error | silent, default info)
--log-limit=... Maximum message count or 0 to disable (default 6)
Expand Down
1 change: 1 addition & 0 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -474,6 +474,7 @@ type Options struct {
TreeShaking bool
DropDebugger bool
MangleQuoted bool
LocalCSSPrefix string
Platform Platform
OutputFormat Format
NeedsMetafile bool
Expand Down
4 changes: 2 additions & 2 deletions internal/linker/linker.go
Original file line number Diff line number Diff line change
Expand Up @@ -493,10 +493,10 @@ func (c *linkerContext) mangleLocalCSS(usedLocalNames map[string]bool) {
nextName := 0

for _, symbolCount := range sorted {
name := minifier.NumberToMinifiedName(nextName)
name := c.options.LocalCSSPrefix + minifier.NumberToMinifiedName(nextName)
for globalNames[name] || usedLocalNames[name] {
nextName++
name = minifier.NumberToMinifiedName(nextName)
name = c.options.LocalCSSPrefix + minifier.NumberToMinifiedName(nextName)
}

// Turn this local name into a global one
Expand Down
2 changes: 2 additions & 0 deletions lib/shared/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,7 @@ function flagsForBuildOptions(
let write = getFlag(options, keys, 'write', mustBeBoolean) ?? writeDefault; // Default to true if not specified
let allowOverwrite = getFlag(options, keys, 'allowOverwrite', mustBeBoolean)
let mangleCache = getFlag(options, keys, 'mangleCache', mustBeObject)
let localCSSPrefix = getFlag(options, keys, 'localCSSPrefix', mustBeString)
keys.plugins = true; // "plugins" has already been read earlier
checkForInvalidFlags(options, keys, `in ${callName}() call`)

Expand Down Expand Up @@ -304,6 +305,7 @@ function flagsForBuildOptions(
if (entryNames) flags.push(`--entry-names=${entryNames}`)
if (chunkNames) flags.push(`--chunk-names=${chunkNames}`)
if (assetNames) flags.push(`--asset-names=${assetNames}`)
if (localCSSPrefix) flags.push(`--local-css-prefix=${localCSSPrefix}`)
if (mainFields) {
let values: string[] = []
for (let value of mainFields) {
Expand Down
2 changes: 2 additions & 0 deletions lib/shared/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,8 @@ export interface BuildOptions extends CommonOptions {
absWorkingDir?: string
/** Documentation: https://esbuild.github.io/api/#node-paths */
nodePaths?: string[]; // The "NODE_PATH" variable from Node.js
/** Documentation: https://esbuild.github.io/api/#local-css-prefix */
localCSSPrefix?: string;
}

export interface StdinOptions {
Expand Down
1 change: 1 addition & 0 deletions pkg/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,7 @@ type BuildOptions struct {
TreeShaking TreeShaking // Documentation: https://esbuild.github.io/api/#tree-shaking
IgnoreAnnotations bool // Documentation: https://esbuild.github.io/api/#ignore-annotations
LegalComments LegalComments // Documentation: https://esbuild.github.io/api/#legal-comments
LocalCSSPrefix string // Documentation: https://esbuild.github.io/api/#local-css-prefix

JSX JSX // Documentation: https://esbuild.github.io/api/#jsx-mode
JSXFactory string // Documentation: https://esbuild.github.io/api/#jsx-factory
Expand Down
19 changes: 19 additions & 0 deletions pkg/api/api_impl.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import (
"github.com/evanw/esbuild/internal/compat"
"github.com/evanw/esbuild/internal/config"
"github.com/evanw/esbuild/internal/css_ast"
"github.com/evanw/esbuild/internal/css_lexer"
"github.com/evanw/esbuild/internal/fs"
"github.com/evanw/esbuild/internal/graph"
"github.com/evanw/esbuild/internal/helpers"
Expand Down Expand Up @@ -524,6 +525,23 @@ func validateJSXExpr(log logger.Log, text string, name string) config.DefineExpr
return config.DefineExpr{}
}

func validateCSSIdentifier(log logger.Log, ident string) string {
for i, c := range ident {
if i == 0 {
if !css_lexer.IsNameStart(c) {
log.AddError(nil, logger.Range{}, fmt.Sprintf("Invalid CSS prefix: %q", ident))
return ""
}
} else {
if !css_lexer.IsNameContinue(c) {
log.AddError(nil, logger.Range{}, fmt.Sprintf("Invalid CSS prefix: %q", ident))
return ""
}
}
}
return ident
}

func validateDefines(
log logger.Log,
defines map[string]string,
Expand Down Expand Up @@ -1257,6 +1275,7 @@ func validateBuildOptions(
MangleProps: validateRegex(log, "mangle props", buildOpts.MangleProps),
ReserveProps: validateRegex(log, "reserve props", buildOpts.ReserveProps),
MangleQuoted: buildOpts.MangleQuoted == MangleQuotedTrue,
LocalCSSPrefix: validateCSSIdentifier(log, buildOpts.LocalCSSPrefix),
DropLabels: append([]string{}, buildOpts.DropLabels...),
DropDebugger: (buildOpts.Drop & DropDebugger) != 0,
AllowOverwrite: buildOpts.AllowOverwrite,
Expand Down
4 changes: 4 additions & 0 deletions pkg/cli/cli_impl.go
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,10 @@ func parseOptionsImpl(
value := arg[len("--mangle-cache="):]
extras.mangleCache = &value

case strings.HasPrefix(arg, "--local-css-prefix=") && buildOpts != nil:
value := arg[len("--local-css-prefix="):]
buildOpts.LocalCSSPrefix = value

case strings.HasPrefix(arg, "--drop:"):
value := arg[len("--drop:"):]
switch value {
Expand Down

0 comments on commit 7c1e87c

Please sign in to comment.