Build ToolsCleancleanJsBuildArtifacts

cleanJsBuildArtifacts

Remove build artifact comments from compiled JavaScript files, including source maps, regions, and ESLint directives.

Overview

cleanJsBuildArtifacts is a utility for cleaning compiled JavaScript files by removing unnecessary build artifact comments.

It processes files based on the provided pattern(s) and removes:

  • Source path comments (e.g. //# sourceURL=...)

    • Removes comment lines that reference file paths containing src/ or node_modules/, commonly emitted by bundlers or transpilers.
    • Supports relative paths (./, ../), varying depths, and optional whitespace.
    //# sourceURL=webpack://./src/index.ts
    //# sourceURL=../node_modules/library/index.js
    //# sourceURL=./src/utils/helper.ts
    // ./src/utils/helper.ts
  • ESLint directive comments (e.g. /* eslint-disable */)

    • Removes inline ESLint control comments used during development, including rule overrides and file-level directives.
    • Supports common patterns such as eslint-disable, eslint-enable, and eslint-disable-next-line.
    /* eslint-disable */
    /* eslint-enable */
    // eslint-disable-next-line no-console
  • Source map references (e.g. //# sourceMappingURL=..., //@ sourceMappingURL=...)

    • Removes inline comments that reference external source map files.
      ➔ See option: removeSourceMap.
  • Source region comments (e.g. // #region, // #endregion, //#region, //#endregion)

    • Removes region markers commonly added by editors or build tools.
      ➔ See option: removeRegion.

Why use this?

  • Prepares clean files for production or distribution.
  • Removes development-only artifacts from build outputs.
  • Helps reduce bundle noise and improve maintainability.

Importing

import { cleanJsBuildArtifacts } from "@rzl-zone/build-tools";
const { cleanJsBuildArtifacts } = require("@rzl-zone/build-tools");

Syntax

cleanJsBuildArtifacts(
  pattern: StringCollection,
  options?: CleanJsArtifactsOptions
): Promise<void>
cleanJsBuildArtifacts(pattern, options?): Promise<void>

Parameters

pattern

Glob pattern or list of patterns that target JavaScript output files.

Accepted values:

  • string ➔ single glob pattern.
  • string[] ➔ multiple glob patterns.
  • Set<string> ➔ unique collection of patterns.

Supported glob features

Patterns support common glob syntax, including:

  • * ➔ match any characters except /.
  • ** ➔ match nested directories.
  • {} ➔ brace expansion (match multiple extensions or patterns).
  • ! ➔ exclude patterns (can be combined with options.patternOptions.ignore).

Info

Pattern resolution behavior can be customized via options.patternOptions (e.g. hidden files, case sensitivity, concurrency, and ignore rules).

File Matching Behavior

  • This utility only processes files that match recognized JavaScript build output formats.
  • This filtering is applied after pattern matching.
  • Supported file types include:
    • .js.
    • .mjs.
    • .cjs.
    • .esm.js.
    • .module.js.

Files that do not match these formats will be automatically ignored, even if they are included in the provided pattern.

Examples:
  • dist/index.js ➔ ✅ processed.
  • dist/index.ts ➔ ❌ ignored.
  • dist/styles.css ➔ ❌ ignored.
  • dist/index.js.map ➔ ❌ ignored.

Examples

TypeScript/JavaScript
// Single pattern
cleanJsBuildArtifacts("dist/**/*.js");

// Multiple patterns
cleanJsBuildArtifacts(["dist/**/*.js", "build/**/*.js"]);

// Using Set
cleanJsBuildArtifacts(new Set(["dist/**/*.js"]));

// With options
cleanJsBuildArtifacts("dist/**/*.{js,cjs,mjs}", {
  patternOptions: {
    ignore: ["**/*.test.js"]
  }
});

// Exclude pattern
cleanJsBuildArtifacts([
  "dist/**/*.{js,cjs,mjs}",
  "!dist/**/*.test.js"
]);

options

Optional configuration object that defines how the utility function should behave in various scenarios, allowing customization and greater control at runtime.


removeSourceMap

  • Description:
    Whether to remove source map reference comments (sourceMappingURL) from output files.

    Detects and removes inline comments that reference source map files, including variations with optional whitespace, different comment prefixes (//# or //@), and different file extensions.

    Common example matches include:

    //# sourceMappingURL=index.js.map
    //@ sourceMappingURL=index.js.map
    //@ sourceMappingURL=index.d.ts.map
    //# sourceMappingURL=index.d.cts.map
    //# sourceMappingURL=index.d.mts.map
  • Required:

  • Type:
    boolean

  • Default:
    false

  • Example:

    TypeScript/JavaScript
    await cleanJsBuildArtifacts(["dist/**/*.js", "build/*/*.mjs"], {
      removeSourceMap: true
    });
    
    // ➔ removes all matching source map reference comments from files

removeRegion

  • Description:
    Whether to remove source region marker comments (e.g. #region, #endregion) from output files.

    Detects and removes single-line region markers commonly used for code folding and logical section grouping.
    Supports variations with leading whitespace, optional spacing between // and #, and trailing text.

    Common example matches include:

    //#region
    //# region
    // #region utils
    // # region utils
    //#endregion
    //# endregion
    // #endregion helpers
    // # endregion helpers

    Notes

    • Matches both opening (#region) and closing (#endregion) markers.
    • Ignores invalid patterns such as #regionX.
  • Required:

  • Type:
    boolean

  • Default:
    true

  • Example:

    TypeScript/JavaScript
    await cleanJsBuildArtifacts(["dist/**/*.js", "build/*/*.mjs"], {
      removeRegion: false
    });
    
    // ➔ keeps region marker comments (disables removal)

removeAdjacentEmptyLines

  • Description:
    Whether to remove empty lines that appear adjacent to removed comments.

    Cleans up leftover blank lines after comment removal to keep output files compact and visually consistent.
    Targets lines that contain only whitespace (e.g. spaces or tabs) or are completely empty.

    Note

    • Matches empty or whitespace-only lines.
    • Preserves lines that contain any visible characters.
    • Typically applied after comment removal (e.g. source maps, regions, etc.).
  • Required:

  • Type:
    boolean

  • Default:
    false

  • Example:

    dist/index.js (Before)
    const a = 1;
    
    
    const b = 2;
    
    //# sourceMappingURL=index.js.map
    TypeScript/JavaScript (Usage)
    await cleanJsBuildArtifacts("dist/**/*.{js,cjs}", {
      removeAdjacentEmptyLines: true
    });
    // Removes empty lines left after comment cleanup
    dist/index.js (After)
    const a = 1;
    const b = 2;
    //# sourceMappingURL=index.js.map

logLevel

  • Description:
    Controls how detailed the logger output should be during execution.

    Supported values

    • silent ➔ no output.
    • error ➔ errors only.
    • info ➔ standard logs (default).
    • debug ➔ verbose logs.

    Notes

    • Invalid values are automatically reset to default.
    • All levels include error output except silent.
  • Required:

  • Type:
    "error" | "silent" | "info" | "debug"

  • Default:
    "info"

  • Example:

    TypeScript/JavaScript
    // Minimal output (errors only)
    await cleanJsBuildArtifacts("dist/**/*.js", {
      logLevel: "error"
    });
    
    // Debug mode (verbose logs)
    await cleanJsBuildArtifacts("dist/**/*.js", {
      logLevel: "debug"
    });
    
    // Silent mode (no logs)
    await cleanJsBuildArtifacts("dist/**/*.js", {
      logLevel: "silent"
    });

patternOptions

  • Description:
    Controls how input file patterns are matched.

    Used to filter or adjust which files are included during processing.
    Useful for ignoring files, handling hidden files, or tweaking matching behavior.

    Behavior

    • Affects which files are selected.
    • Can exclude unwanted files (e.g. test files).
    • Falls back to default configuration when invalid type or not provided.
  • Required:

  • Type:
    object

  • Default:

    {
      absolute: false,
      baseNameMatch: false,
      caseSensitiveMatch: true,
      concurrency: os.cpus().length,
      dot: true,
      followSymbolicLinks: true,
      globstar: true,
      ignore: [],
      markDirectories: false,
      objectMode: false,
      onlyDirectories: false,
      onlyFiles: true,
      unique: true,
      throwErrorOnBrokenSymbolicLink: false
    }
  • Example:

    TypeScript/JavaScript
    // Ignore source maps
    await cleanJsBuildArtifacts("dist/**/*.{js,cjs}", {
      patternOptions: {
        ignore: ["**/*.map"]
      }
    });
    
    // Case-insensitive matching
    await cleanJsBuildArtifacts("dist/**/*.{js,cjs}", {
      patternOptions: {
        caseSensitiveMatch: false
      }
    });
    
    // Disallowing patterns to match entries that begin with a period (.).
    await cleanJsBuildArtifacts("dist/**/*.{js,cjs}", {
      patternOptions: {
        dot: false
      }
    });

Returns

Returns a Promise<void>.
The function performs asynchronous file processing and does not return any value.

Version information

  • Since: v0.0.7.
  • Category: clean.
  • Stability: Stable (Production-ready).
Made with ❤️ by @rzl-app