7 javascript node.js npm typescript
如何使用定义文件创建 NPM 包,其中仅在*.ts文件中声明接口。
假设我们有两个接口和一个类定义:
export interface A {
id: number;
}
export interface B {
name: string;
}
export class C {
}
Run Code Online (Sandbox Code Playgroud)
我需要将这些*.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"
}
Run Code Online (Sandbox Code Playgroud)
我的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
}
Run Code Online (Sandbox Code Playgroud)
里面index.ts有:
import { A } from "./a";
import { B } from "./b";
import { C } from "./c";
Run Code Online (Sandbox Code Playgroud)
'./a', './b', './c'带有接口和类声明的文件在哪里。
当我index.js使用命令将它构建到文件时:tsc index.ts然后我无法访问index.js在其他项目中使用模块的接口(npm install)
要将这些类型与您的包捆绑在一起,您需要做两件事:
"declaration"为true在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 <----------------------
}
}
Run Code Online (Sandbox Code Playgroud)
包.json
{
"name": "my-package",
"version": "1.0.0",
"main": "index.js",
"types": "index.d.ts", <----------------------
"license": "ISC",
"devDependencies": {
"typescript": "^3.8.3"
}
}
Run Code Online (Sandbox Code Playgroud)
这是GitHub 上为您提供的一个工作示例。所有上述内容和更多详细信息都隐藏在文档中。
| 归档时间: |
|
| 查看次数: |
208 次 |
| 最近记录: |