gpt4 book ai didi

node.js - typescript 生成的定义文件(.d.ts)不适用于 package.json 类型

转载 作者:IT老高 更新时间:2023-10-28 23:26:54 25 4
gpt4 key购买 nike

我使用 tsc 编译器的 --declaration 参数从我的 typescript 项目创建了一个定义文件 (d.ts)。

但是当我尝试在 npm package.json 上发布具有属性 typings 的包时,这个生成的定义文件显然不起作用。我创建了另一个项目来测试它。

它报错:“Exported external package file typings file '...d.ts' 不是模块。请联系包作者更新包定义”。 p>

这是我的源文件:

MyInterface.ts

export interface MyInterface
{
MyProperty: string;
}

MyClass.ts

import {MyInterface} from './MyInterface';

export class MyClass implements MyInterface
{
get MyProperty(): string
{
return "MyString";
}
}

MyInheritedClass.ts

import {MyClass} from './MyClass';

export class MyInheritedClass extends MyClass
{
public MyMethod(): number
{
return 1;
}
}

tsc 命令是这样的:

tsc MyClass.ts MyInterface.ts MyInheritedClass.ts --declaration -t es5 -outFile "mydefinition.js" --module "system"

这是生成的定义:

mydefinition.d.ts

declare module "MyInterface" {
export interface MyInterface {
MyProperty: string;
}
}
declare module "MyClass" {
import { MyInterface } from "MyInterface";
export class MyClass implements MyInterface {
MyProperty: string;
}
}
declare module "MyInheritedClass" {
import { MyClass } from "MyClass";
export class MyInheritedClass extends MyClass {
MyMethod(): number;
}
}

我还有其他事情要做吗,或者生成的定义在 package.json 类型中不起作用??

更新详情:

场景是我有 2 个项目:

  • 第一个项目是我生成要发布到 npm 的库的地方,而 package.json 是我将类型属性链接到由 tsc -d 命令生成的 mydefinition.d.ts 文件的地方.

  • 我创建的第二个项目通过添加生成的包(带类型)来测试第一个项目。

两个项目的链接和场景的另一个链接:

https://github.com/jvitor83/typings-packagejson

我认为问题在于第一个链接中的“您的定义文件应作为外部模块编写”。但我想知道是否有办法让生成的这些定义放在 package.json 的类型属性中。

重现问题:

最佳答案

The solution was:

1 - 添加单个文件“index.ts”,用于导出所有其他文件。

export * from "./MyInterface"
export * from "./MyClass"
export * from "./MyInheritedClass"

2 - 在构建过程中添加两个文件的编译/转译(一个用于声明,另一个用于单个 js 文件 [在 tsc 编译器中没有属性])

let tsConfigDeclaration = gulp_typescript({module: 'system', target: 'es5', declaration: true, removeComments: true });
let tsConfigOneFile = gulp_typescript({module: 'system', target: 'es5', declaration: true, removeComments: true, out: 'typings-packagejson.js'});

构建过程中的更多信息:https://github.com/jvitor83/typings-packagejson/blob/master/gulpfile.js

和索引文件:https://github.com/jvitor83/typings-packagejson/blob/master/app/src/typings-packagejson.ts

关于node.js - typescript 生成的定义文件(.d.ts)不适用于 package.json 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37091321/

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