dts-bundle-generator

repository·master·Indexed 21 days ago

https://github.com/timocov/dts-bundle-generator

A tool for creating a single, consolidated .d.ts bundle from TypeScript source code. It helps produce clean, production-ready type definitions by avoiding the module fragmentation typically produced by standard tsc bundling. It supports CLI usage and configuration via JSON or JavaScript files, allowing control over external inlines, imports, and @types references.

Tokens
6.9K
Snippets
10
Records
24
Agent score
73%

What's inside dts-bundle-generator

  1. Create a configuration file for dts-bundle-generator

    master

    You can configure dts-bundle-generator using either a JSON file or a JavaScript file with a CommonJS export (module.exports).

    To ensure your JavaScript configuration is valid, you can use the @ts-check JSDoc comment at the top of your file. This allows you to leverage TypeScript type checking for your config object. Alternatively, you can write your configuration in TypeScript and compile it to JavaScript before running the generator.

    // @ts-check
    
    /** @type {import('dts-bundle-generator/config-schema').BundlerConfig} */
    const config = {
        // ... config content
    };
    
    module.exports = config;
  2. Configure external inlines, imports, and types

    master

    You can control how external dependencies from node_modules or @types are handled in the generated bundle:

    • --external-inlines: An array of package names to inline their typings directly into the output file.
    • --external-imports: An array of package names to import using standard import { ... } from 'library-name' syntax. By default, all libraries are imported except those inlined or from @types.
    • --external-types: An array of package names from @types to import via triple-slash reference directives.

    Important: When using arguments that accept arrays (like --external-inlines or --external-imports) before the positional input files, use the -- separator to prevent the tool from misinterpreting the input files as part of the array.

    # Example: Inlining one package and importing others
    ./node_modules/.bin/dts-bundle-generator \
      --external-inlines=@mycompany/internal-project \
      --external-imports=@angular/core rxjs \
      -- path/to/your/entry-file.ts
    
    # Example: Using external types (e.g., jquery)
    ./node_modules/.bin/dts-bundle-generator --external-types=jquery path/to/your/entry-file.ts
  3. Install dts-bundle-generator

    master

    You can install dts-bundle-generator as a development dependency or globally via npm.

    Prerequisite: You must enable the declaration compiler option in your tsconfig.json for the tool to work.

    # Install as a dev dependency
    npm install --save-dev dts-bundle-generator
    
    # Or install globally
    npm install -g dts-bundle-generator
  4. Use dts-bundle-generator via CLI

    master

    The CLI tool generates a single .d.ts bundle from your TypeScript entry files. This is useful when you want to avoid the fragmented module declarations produced by tsc and instead want a single, clean definition file that only exports what is actually used by your entry points.

    Basic Usage: dts-bundle-generator [options] <file(s)>

    # Generate a bundle for a single entry file
    ./node_modules/.bin/dts-bundle-generator -o my.d.ts path/to/your/entry-file.ts
    
    # Generate a bundle for multiple entry files
    ./node_modules/.bin/dts-bundle-generator path/to/your/entry-file.ts path/to/your/entry-file-2.ts
  5. Use the dts-bundle-generator CLI

    master

    The dts-bundle-generator CLI is used to bundle TypeScript declaration files (.d.ts) into a single file. You can provide one or more entry files. If you provide multiple entry files, you cannot use the --out-file option; instead, the generator will create a .d.ts file for each entry in its corresponding directory.

    Basic Usage:

    # Generate a bundle for a single entry file
    dts-bundle-generator path/to/your/entry-file.ts
    
    # Generate a bundle for multiple entry files
    dts-bundle-generator path/to/file1.ts path/to/file2.ts
    
    # Specify a custom output file for a single entry
    dts-bundle-generator path/to/entry.ts --out-file path/to/output.d.ts
    
    # Use a specific configuration file
    dts-bundle-generator --config path/to/config.json path/to/entry.ts
    
    # Use a specific tsconfig.json for compilation
    dts-bundle-generator --project path/to/tsconfig.json path/to/entry.ts
    
    # Use triple-slash references for specific @types packages
    dts-bundle-generator --external-types jquery react -- entry-file.ts
    #!/usr/bin/env node
    
    # Example usage from CLI documentation
    $0 path/to/your/entry-file.ts
    $0 path/to/your/entry-file.ts path/to/your/entry-file-2.ts
    $0 --external-types jquery react -- entry-file.ts
  6. Example JSON configuration

    master

    A sample JSON configuration demonstrating multiple entries, library inlining, and output formatting.

    {
        "compilationOptions": {
            "preferredConfigPath": "./tsconfig.json"
        },
    
        "entries": [
            {
                "filePath": "./src/index.ts",
                "outFile": "./out/index.d.ts",
                "libraries": {
                    "inlinedLibraries": ["@my-company/package"]
                },
                "output": {
                    "inlineDeclareGlobals": false,
                    "sortNodes": true,
                    "umdModuleName": "MyModuleName"
                }
            },
            {
                "filePath": "./src/second.ts",
                "outFile": "./out/second.d.ts",
                "failOnClass": true,
                "libraries": {
                    "allowedTypesLibraries": [],
                    "importedLibraries": [],
                    "inlinedLibraries": []
                }
            },
            {
                "filePath": "./src/third.ts"
            }
        ]
    }
  7. Example JavaScript configuration with type checking

    master

    A sample JavaScript configuration using @ts-check and importing types from dts-bundle-generator/config-schema to provide autocompletion and validation.

    // @ts-check
    
    // If won't use `@ts-check` - just remove that comments (with `@type` JSDoc below).
    
    /** @type import('dts-bundle-generator/config-schema').OutputOptions */
    const commonOutputParams = {
        inlineDeclareGlobals: false,
        sortNodes: true,
    };
    
    /** @type import('dts-bundle-generator/config-schema').BundlerConfig */
    const config = {
        compilationOptions: {
            preferredConfigPath: './tsconfig.json',
        },
    
        entries: [
            {
                filePath: './src/index.ts',
                outFile: './out/index.d.ts',
                noCheck: false,
    
                output: commonOutputParams,
            },
    
            {
                filePath: './src/second.ts',
                outFile: './out/second.d.ts',
                failOnClass: true,
    
                libraries: {
                    inlinedLibraries: ['@my-company/package'],
                },
    
                output: commonOutputParams,
            },
        ],
    };
    
    module.exports = config;
  8. Configure output format with OutputOptions

    master

    Use the OutputOptions object to control the visual and structural characteristics of the generated .d.ts file.

    OptionTypeDescription
    umdModuleNamestringIf provided, appends export as namespace <name>; to the end of the file, enabling UMD compatibility.
    sortStatementsbooleanIf true, the top-level statements in the output will be sorted alphabetically.
    noBannerbooleanIf true, the version banner comment (// Generated by dts-bundle-generator v...) will be omitted.
  9. Configure UMD module name and output formatting

    master

    When generating the bundle, you can control the following output options:

    • umdModuleName: Specifies the name of the module when generating a UMD bundle.
    • sortNodes: A boolean flag to determine if statements in the output should be sorted.
    • noBanner: A boolean flag to prevent the inclusion of a banner in the output.
  10. Configure dts-bundle-generator via a config file

    master

    You can provide configuration to dts-bundle-generator using a configuration file. The configuration object must follow the BundlerConfig structure, which includes a list of entry points and optional compilation options.

    BundlerConfig Structure

    entries (Required)

    An array of ConfigEntryPoint objects. Each entry defines what to bundle and how.

    ConfigEntryPoint properties:

    • filePath (Required): The path to the input TypeScript file.
    • outFile (Optional): The path where the generated .d.ts file will be saved. If omitted, the output file will have the same name as the input file but with a .d.ts extension.
    • noCheck (Optional): A boolean that, if set to true, skips the validation of the generated .d.ts file.
    • failOnClass (Optional): A boolean indicating whether to fail if a class is encountered.
    • libraries (Optional): Configuration for handling libraries:
      • allowedTypesLibraries: Array of strings.
      • importedLibraries: Array of strings.
      • inlinedLibraries: Array of strings.
    • output (Optional): Configuration for the output format:
      • inlineDeclareGlobals: boolean
      • inlineDeclareExternals: boolean
      • sortNodes: boolean
      • umdModuleName: string
      • noBanner: boolean
      • respectPreserveConstEnum: boolean
      • exportReferencedTypes: boolean

    compilationOptions (Optional)

    Global settings for the compilation process.

    CompilationOptions properties:

    • followSymlinks: boolean
    • preferredConfigPath: string (Path to a preferred configuration file)

    Example Configuration

    {
      "entries": [
        {
          "filePath": "src/index.ts",
          "outFile": "dist/index.d.ts",
          "noCheck": false,
          "output": {
            "sortNodes": true
          }
        }
      ],
      "compilationOptions": {
        "followSymlinks": true
      }
    }
  11. Configure output formatting with `OutputOptions`

    master

    Use OutputOptions within an EntryPointConfig to control how the generated .d.ts file is structured and styled.

    KeyTypeDescription
    sortNodesbooleanSort output nodes in ascendant order.
    umdModuleNamestringName of the UMD module. If specified, export as namespace ModuleName; will be emitted.
    inlineDeclareGlobalsbooleanEnables inlining of declare global statements from inlined files.
    inlineDeclareExternalsbooleanEnables inlining of declare module 'external-module' {} statements from inlined files.
    noBannerbooleanRemoves the "Generated by dts-bundle-generator" comment from the output.
    respectPreserveConstEnumbooleanStrips the const keyword from direct-exported const enum to avoid TypeScript issues.
    exportReferencedTypesbooleanIf false, nodes are only exported if they are exported from the root source file (disables automatic exporting of all used types/interfaces).
  12. Configure ConstEnum stripping behavior

    master

    The generator can strip the const keyword from const enum declarations in the output. This behavior is controlled by the interaction between your TypeScript compiler options and the respectPreserveConstEnum option in the generator configuration.

    • The generator checks if preserveConstEnums is enabled in your compilerOptions.
    • If respectPreserveConstEnum is set to true in the generator options, the const keyword will be stripped if the enum is part of the root file's exports.