Bha*_*ngh 4 node.js npm typescript
我想发布一个 typescript npm 包,嵌入类型。我的文件夹结构如下
dist/
[...see below]
src/
global.d.ts
index.ts
otherfile.ts
test/
examples/
Run Code Online (Sandbox Code Playgroud)
举个例子,我的 global.d.ts 文件包含与整个项目相关的类型。我的index.d.ts 文件使用这些类型并导出函数。
//global.d.ts
interface Dog {
name: string,
age: number
}
//more types...
Run Code Online (Sandbox Code Playgroud)
//index.ts
import {func1, func2} from './otherfile.ts'
export default function getDogName(dog: Dog): string {
return dog.name
}
export {func1, func2}
Run Code Online (Sandbox Code Playgroud)
我可以构建这段代码,并且一切都可以正确运行,因此 typescript 知道global.d.ts. 然而,当我运行 tsc (使用下面的配置)时,它会在我的dist/文件夹中生成文件,但其中不包含该global.d.ts文件。即: dist 仅包含index.d.ts和otherfile.d.ts。不应该dist/还包含吗global.d.ts?如果不是 - 安装我的软件包的人如何知道 Dog 的类型?
我的构建时间配置如下所示。
//tsconfig.json
{
"extends": "./tsconfig.base.json",
"compilerOptions": {
"outDir": "dist/",
"declaration": true
},
// Only point to typings and the start of your source, e.g. `src/index.ts`
"include": [ "src/*"],
"exclude": ["node_modules", "examples", "test"]
}
Run Code Online (Sandbox Code Playgroud)
作为参考,实际的存储库位于:https://github.com/bhaviksingh/lsystem
好吧:)经过多次实验,我想分享我所做的事情。可能有更好的解决方案(很想找到它们),但 TLDR 是我将其从全局声明文件更改为常规 TS 模块,并导出/导入所有类型。
所以我将global.d.ts文件重命名为interfaces.ts,然后导出类型。
//interfaces.ts (renamed from global.d.ts)
export interface Dog {
name: string,
age: number
}
//more types...
Run Code Online (Sandbox Code Playgroud)
我将此类型导入index.d.ts并重新导出
//index.ts
import Dog from "./interfaces"
export {Dog}
Run Code Online (Sandbox Code Playgroud)
TSConfig 知道编译这些声明
//tsconfig.global.json
{
"extends": "./tsconfig.base.json",
"compilerOptions": {
"outDir": "dist/",
"declaration": true
},
// Only point to typings and the start of your source, e.g. `src/index.ts`
"include": [ "src/*"],
"exclude": ["node_modules", "examples/", "test/"]
}
Run Code Online (Sandbox Code Playgroud)
我的 package.json 指向已编译的声明文件。
//package.json
{
//...
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
//...
"build": "tsc -p tsconfig.global.json",
},
}
Run Code Online (Sandbox Code Playgroud)
可能有更好的解决方案,可能包括/// <reference path="..." /> 标签,但这就是我现在拥有的并且它有效。当人们安装我的库时,他们可以访问智能感知中的类型,如果他们想使用可以导入的类型。
| 归档时间: |
|
| 查看次数: |
2278 次 |
| 最近记录: |