【问题标题】:How to create npm package with definition files?如何使用定义文件创建 npm 包?
【发布时间】:2020-07-05 10:06:08
【问题描述】:

如何使用定义文件创建 NPM 包,其中仅在 *.ts 文件中声明接口。

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

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' 是带有接口和类声明的文件。

当我使用命令将它构建到index.js 文件时:tsc index.ts 然后我无法在其他项目中使用模块index.js 访问接口(npm install)

【问题讨论】:

    标签: javascript node.js typescript npm


    【解决方案1】:

    要将类型与您的包捆绑在一起,您需要做两件具体的事情:

    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"
      }
    }
    

    这是working example for you on GitHub。以上所有内容和更多详细信息是hidden in the documentation

    【讨论】:

      【解决方案2】:

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

      1. 与您的 npm 包捆绑,
      2. 或发布到 npm 上的 @types organization

      这里是the documentation 来帮助你

      【讨论】:

      • 那么,你的意思是有两个包,一个是实现包,另一个是声明@types?在我的情况下是什么?
      • 当你使用 TypeScript 时,你可以使用第一个选项
      猜你喜欢
      • 1970-01-01
      • 2018-07-14
      • 1970-01-01
      • 2019-08-15
      • 2016-03-05
      • 2017-08-27
      • 2021-12-18
      • 2016-05-09
      • 2020-07-19
      相关资源
      最近更新 更多