網站搜尋

typescript - 使用 "export" 而不是 "main" 時,如何在 package.json 中打包 "types" 欄位


在為 Typescript NPM 套件使用 package.json 的 "main" 欄位時,本文件說明如何將型別(作為 .d.ts 檔案)與輸出的 JS 檔一起發佈。

package.json 也允許使用 "exports" 欄位而不是 "main" 來指定多個進入點、多個 js 檔案。

但是在那種情況下,這些不同入口點的各個 .d.ts 文件應該如何在 package.json 中指定呢?

答案#1

您可以為每個匯出選項單獨指定 d.ts 文件。此功能出現在 TS 4.7

範例:

// package.json
{
    "name": "my-package",
    "type": "module",
    "exports": {
        ".": {
            // Entry-point for `import "my-package"` in ESM
            "import": {
                // Where TypeScript will look.
                "types": "./types/esm/index.d.ts",

                // Where Node.js will look.
                "default": "./esm/index.js"
            },
            // Entry-point for `require("my-package") in CJS
            "require": {
                // Where TypeScript will look.
                "types": "./types/commonjs/index.d.cts",

                // Where Node.js will look.
                "default": "./commonjs/index.cjs"
            },
        }
    },

    // Fall-back for older versions of TypeScript
    "types": "./types/index.d.ts",

    // CJS fall-back for older versions of Node.js
    "main": "./commonjs/index.cjs"
}

或者一些真實的例子。來自 stylelint 套件:

"exports": {
    ".": {
      "import": {
        "types": "./types/stylelint/index.d.mts",
        "default": "./lib/index.mjs"
      },
      "require": {
        "types": "./types/stylelint/index.d.ts",
        "default": "./lib/index.cjs"
      }
    },
    "./package.json": "./package.json",
    "./lib/utils/*": "./lib/utils/*"
  },
  "main": "lib/index.cjs",
  "types": "types/stylelint/index.d.ts",