javascriptnode.jstypescriptviterollup

Producing types for CommonJS Modules with vite-plugin-dts?


I was reading up on how to use Vite's library mode to produce an NPM package here and the common way to set the relevant package fields for a typescript library seems to be:

  "main": "./dist/my-lib.umd.cjs",
  "module": "./dist/my-lib.js",
  "types": "./dist/index.d.ts",
  "exports": {
    ".": {
      "import": "./dist/my-lib.js",
      "require": "./dist/my-lib.umd.cjs"
    }
  }

And so this produces a package that can be used both with node require and esm imports.

However I was also reading this package exports which says that types have to be declared for both commonjs and esm modules like this (This outlines the various reasons why ...):

    "exports": {
        // For CJS
        "require": {
            "types": "./dist/index.d.cts", // require + types = CJS types
            "default": "./dist/index.cjs"  // require = CJS code
        },
        // For ESM
        "import": {
            "types": "./dist/index.d.mts", // import + types = ESM types
            "default": "./dist/index.mjs"  // import = ESM code
        }
    }

Does vite-plugin-dts know how to produce types for both the UMD and the ESM bundles that the vite library mode produces?

Or does anyone know if there is a different way of producing the UMD bundle types?

Update

I found some more information in this typescript issue here..

It seems like the need to provide separate types for CommonJS and ESM environments is only a concern when hand authoring types, which of course the vite build is not doing, so just wanted to confirm that this is the case.


Solution

  • There is no need for a different .d.ts file. The .d.ts file describes the API shape of your library. It's independent of the bundler format (in most cases).

    The first package.json example you provided is the recommended way for libraries:

    
      "main": "./dist/my-lib.umd.cjs", // For older CJS envs
      "module": "./dist/my-lib.js",   // For ESM-aware bundlers
      "types": "./dist/index.d.ts", // THE type definitions for your library
      "exports": {
        ".": {
          "types": "./dist/index.d.ts", // Explicitly declare types for modern resolution
          "import": "./dist/my-lib.js", // Points to ESM bundle
          "require": "./dist/my-lib.umd.cjs" // Points to CJS/UMD bundle
        }
      }