如何创建带有定义文件的npm包?

8

如何创建一个包含仅在 *.ts 文件中声明接口的定义文件的 NPM 包。

假设我们有两个接口和一个类定义:

export interface A {
 id: number;
}

export interface B {
 name: string;
}

export class C {
}

我需要将这些*.ts文件打包到npm包中,应该如何操作?我应该在index.ts中导出它们吗?

我的package.json文件如下:

{
  "name": "npm",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

我的 tsconfig.json 文件如下:

"compilerOptions": {
   "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
   "module": "commonjs",
   "strict": true, 
   "esModuleInterop": true, 
   "forceConsistentCasingInFileNames": true   
}

index.ts文件中有以下内容:
import { A } from "./a";
import { B } from "./b";
import { C } from "./c";

其中'./a', './b', './c'是包含接口和类声明的文件。

当我使用命令tsc index.ts将其构建为index.js文件时,我不能在其他项目(npm install)中使用模块index.js来访问接口。

2个回答

4

若要将类型与您的软件包捆绑在一起,您需要完成两件特定的事情:

  1. tsconfig.json中设置 "declaration"这会告诉TypeScript生成*.d.ts文件。
  2. package.json中设置 "types"这会告诉TypeScript在哪里找到生成的*.d.ts文件。

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "strict": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "declaration": true  <----------------------
  }
}

package.json

{
  "name": "my-package",
  "version": "1.0.0",
  "main": "index.js",
  "types": "index.d.ts", <----------------------
  "license": "ISC",
  "devDependencies": {
    "typescript": "^3.8.3"
  }
}

这里有一个GitHub上的工作示例供您参考。所有上述内容和更多细节都隐藏在文档中


1

发布定义文件有两种方法:

  1. 将其与您的npm软件包捆绑在一起,
  2. 或将其发布到npm上的@types organization

这里是相关文档以帮助您完成此操作。


所以,你的意思是有两个包,一个是实现包,另一个是声明 @types 包?在我的情况下,它是什么? - user13118582
由于您正在使用TypeScript,因此您可以使用第一种选项。 - Ghassen Rjab

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接