Build ToolsGenerategenerateReferenceIndex

generateReferenceIndex

Generates a TypeScript reference index file (.d.ts) from matched declaration and module output files.

Overview

generateReferenceIndex generates a TypeScript declaration reference index file (.d.ts) from matched output files.

It scans declaration and supported module outputs, then creates a single aggregated entry file containing TypeScript reference directives and optional re-export statements.


Why use this?

  • Combine multiple declaration outputs into one entry point.
  • Supports glob patterns and multiple input sources.
  • Optional export * from type generation.
  • Helps simplify package type distribution.
  • Deterministic and repeatable output.

Importing

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

Syntax

generateReferenceIndex(
  pattern: StringCollection,
  options: GenerateReferenceOptions
): Promise<void>
generateReferenceIndex(pattern, options): Promise<void>

Parameters

pattern

Glob pattern or list of patterns used to match declaration and module output files.

  • Accepted values:

    • string ➔ single glob pattern.
    • string[] ➔ multiple glob patterns.
    • Set<string> ➔ unique collection of patterns.
  • Supported matched file extensions include:

    • .d.ts.
    • .d.mts.
    • .d.cts.
    • .js.
    • .mjs.
    • .cjs.
  • When onlyDeclarations is true (default), matched files are filtered to standard declaration formats only:

    • .d.ts.
    • .d.mts.
    • .d.cts.
  • When onlyDeclarations is false, all matched supported files are eligible.

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 also be combined with options.patternOptions.ignore).

Info

Pattern resolution behavior can be customized via options.patternOptions such as hidden files, case sensitivity, concurrency, and ignore rules.

File Matching Behavior

  • Pattern matching happens first based on the provided glob input.
  • Extension filtering happens after matching.
  • Files with unsupported extensions are automatically ignored.
Examples:
  • dist/index.d.ts ➔ ✅ included by default.
  • dist/index.d.mts ➔ ✅ included by default.
  • dist/index.d.cts ➔ ✅ included by default.
  • dist/index.js ➔ ✅ included when onlyDeclarations: false.
  • dist/index.ts ➔ ❌ ignored unless explicitly matched and onlyDeclarations: false.
  • dist/styles.css ➔ ❌ ignored.
  • dist/index.js.map ➔ ❌ ignored.

Examples

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

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

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

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

// Exclude pattern
generateReferenceIndex([
  "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.


outDir

  • Description:
    Directory where the generated index file will be written.

    Used as the base path for the final generated declaration file.

  • Required:

  • Type:
    string

  • Default:
    "dist/.references"

  • Example:

    TypeScript/JavaScript
    await generateReferenceIndex(["dist/**/*.js", "build/*/*.mjs"], {
      outDir: "dist/types/refs"
    });

Notes

  • Value is normalized before use.
  • Leading and trailing whitespace is trimmed.
  • Trailing slash is removed automatically.
  • Empty results are not rejected by this function unless validated elsewhere.

outFileName

  • Description:
    File name used for the generated declaration index output.

  • Required:

  • Type:
    boolean

  • Default:
    "index.d.ts"

  • Example:

    TypeScript/JavaScript
    await generateReferenceIndex(["dist/**/*.js", "build/*/*.mjs"], {
      outFileName: "index.d.cts"
    });

Validation Behavior

  • Must be a file name only, not a path.
  • Forward slash / and backslash \ are not allowed.
  • Leading and trailing whitespace is trimmed before use.
  • Throws an error when the value contains / or \.
Examples:
  • " index.d.cts ""index.d.cts"
  • " index.d.mts ""index.d.mts"
  • "dist/index.d.ts" ➔ ❌ throws Invalid outFileName
  • "../index.d.ts" ➔ ❌ throws Invalid outFileName
  • "..\\index.d.ts" ➔ ❌ throws Invalid outFileName

withExportTypes

  • Description:
    Enables generation of additional type export * from "..." statements for resolved modules.

    When enabled, the output file contains both TypeScript reference paths and aggregated module re-exports.

  • Required:

  • Type:
    boolean

  • Default:
    false

  • Example:

    TypeScript/JavaScript
    await generateReferenceIndex(["dist/**/*.js", "build/*/*.mjs"], {
      withExportTypes: true
    });

    Result (dist/.references/index.d.ts):

    TypeScript/JavaScript
    // References Paths:
    /// <reference path="../types/user.d.ts" />
    /// <reference path="../types/user.d.cts" />
    /// <reference path="../types/post.d.ts" />
    /// <reference path="../types/post.d.cts" />
    
    // Exported Types:
    export * from "../types/user";
    export * from "../types/post";

inputDirReference

  • Description:
    Base directory used for resolving reference paths.

    Used to compute relative paths inside the generated index file.

  • Required:

  • Type:
    string

  • Default:
    "dist"

  • Example:

    TypeScript/JavaScript
    await generateReferenceIndex(
      [
        "dist/types/**/*.d.ts",
        "dist/generated/**/*.d.{js,cjs,mjs}"
      ],
      {
        inputDirReference: "dist"
      }
    );

    Result (dist/.references/index.d.ts):

    TypeScript/JavaScript
    // References Paths:
    /// <reference path="../types/user.d.ts" />
    /// <reference path="../generated/schema.d.js" />
    /// <reference path="../generated/config.d.cjs" />

Behavior

  • Used as the base path when generating relative reference targets.
  • Matching files under this directory will have the leading base path removed before output generation.
  • Useful when combining multiple input folders under one shared root.

Normalization

  • Leading and trailing whitespace is trimmed.
  • Trailing slash / is removed automatically.
Examples:
  • "dist/""dist"
  • " dist ""dist"

onlyDeclarations

  • Description:
    Restricts matched input files to TypeScript declaration files only.

    When enabled, only .d.ts, .d.mts, and .d.cts files are included after glob matching.

  • Required:

  • Type:
    boolean

  • Default:
    true

  • Example:

    • example 1:
    TypeScript/JavaScript
    await generateReferenceIndex(
      "dist/**/*",
      {
        onlyDeclarations: true
      }
    );

    Result (dist/.references/index.d.ts):

    TypeScript/JavaScript
    // References Paths:
    /// <reference path="../types/user.d.ts" />
    /// <reference path="../types/post.d.cts" />

    • example 2:
    TypeScript/JavaScript
    await generateReferenceIndex(
      "dist/**/*",
      {
        onlyDeclarations: false
      }
    );

    Result (dist/.references/index.d.ts):

    TypeScript/JavaScript
    // References Paths:
    /// <reference path="../models/order.ts" />
    /// <reference path="../models/user.js" />
    /// <reference path="../models/another.cjs" />

Behavior

  • Filtering is applied after files are matched by the provided glob patterns.
  • When true, non-declaration files such as .js, .mjs, .cjs, .ts, .mts, and .cts are excluded.
  • When false, all matched supported files remain eligible for reference generation.
  • Useful to prevent accidental inclusion of source files or JavaScript build outputs.

Examples

  • Pattern "dist/**/*.d.ts" + true ➔ no practical change.
  • Pattern "dist/**/*" + true ➔ only declaration files kept.
  • Pattern "dist/**/*.js" + true ➔ no files included.
  • Pattern "dist/**/*.ts" + true ➔ only matching generated .d.ts style declarations are included when available.

  • Description:
    Controls the banner text prepended to the generated output file.

    The banner is inserted at the top of the generated reference index file before reference paths and export statements.

  • Required:

  • Type:
    boolean | string | Promise<string>

  • Default:
    true

  • Example:

    • example 1:
    TypeScript/JavaScript
    await generateReferenceIndex(
      "dist/**/*",
      {
        banner: true
      }
    );

    Result (dist/.references/index.d.ts):

    TypeScript/JavaScript
    /*!
      * ========================================================================
      *  @my-org/my-package
      * ------------------------------------------------------------------------
      *  Version: `1.2.3`
      *  Author: `John Doe`
      *  Repository: `https://github.com/my-org/my-package`
      * ========================================================================
      */
    
    // References Paths:
    /// <reference path="../types/user.d.ts" />

    • example 2:
    TypeScript/JavaScript
    await generateReferenceIndex(
      "dist/**/*",
      {
        banner: false
      }
    );

    Result (dist/.references/index.d.ts):

    TypeScript/JavaScript
    // References Paths:
    /// <reference path="../types/user.d.ts" />

    • example 3:
    TypeScript/JavaScript
    await generateReferenceIndex(
      "dist/**/*",
      {
        banner: "/* Custom Build Banner */"
      }
    );

    Result (dist/.references/index.d.ts):

    TypeScript/JavaScript
    /* Custom Build Banner */
    
    // References Paths:
    /// <reference path="../types/user.d.ts" />
    • example 4:
    TypeScript/JavaScript
    await generateReferenceIndex(
      "dist/**/*",
      {
        banner: Promise.resolve("/* Async Banner */")
      }
    );

    Result (dist/.references/index.d.ts):

    TypeScript/JavaScript
    /* Async Banner */
    
    // References Paths:
    /// <reference path="../types/user.d.ts" />

Behavior

  • true uses an automatically generated banner from package.json via generatePackageBanner().
  • false disables banner injection entirely.
  • string uses the provided custom banner text as-is.
  • Promise<string> is awaited, then the resolved value is used as banner text.
  • Empty or non-string resolved values produce no banner output.

Output Notes

  • Banner content is written before all generated lines.
  • A line break is appended after generated automatic banners.
  • The final output file always ends with a trailing newline.
  • Custom banner content should already be properly formatted.

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 cleanTypesBuildArtifacts("dist/**/*.{d.ts,d.cts,d.mts}", {
      logLevel: "error"
    });
    
    // Debug mode (verbose logs)
    await cleanTypesBuildArtifacts("dist/**/*.{d.ts,d.cts,d.mts}", {
      logLevel: "debug"
    });
    
    // Silent mode (no logs)
    await cleanTypesBuildArtifacts("dist/**/*.{d.ts,d.cts,d.mts}", {
      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 cleanTypesBuildArtifacts("dist/**/*.{d.ts,d.cts,d.mts}", {
      patternOptions: {
        ignore: ["**/*.map"]
      }
    });
    
    // Case-insensitive matching
    await cleanTypesBuildArtifacts("dist/**/*.{d.ts,d.cts,d.mts}", {
      patternOptions: {
        caseSensitiveMatch: false
      }
    });
    
    // Disallowing patterns to match entries that begin with a period (.).
    await cleanTypesBuildArtifacts("dist/**/*.{d.ts,d.cts,d.mts}", {
      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: generate.
  • Stability: Stable (Production-ready).
Made with ❤️ by @rzl-app