gpt4 book ai didi

javascript - 如何使用定义文件创建 npm 包?

转载 作者:行者123 更新时间:2023-12-01 15:10:07 24 4
gpt4 key购买 nike

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

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

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

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

最佳答案

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

  • 设置 "declaration"tsconfig.json . 这告诉 TypeScript 生成 *.d.ts文件。
  • 设置 "types"package.json . 这告诉 TypeScript 在哪里可以找到生成的 *.d.ts文件。

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

    包.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 .

    关于javascript - 如何使用定义文件创建 npm 包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60839051/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com