gpt4 book ai didi

node.js - 自动将 Typescript 定义文件包装到模块中

转载 作者:太空宇宙 更新时间:2023-11-04 00:38:50 28 4
gpt4 key购买 nike

我很可能在这里缺少一些 tsconfig 选项。

我所做的事情非常简单:

我正在创建一个 npm 模块,例如:

export class HelloWorld {
constructor(public greeting: string){}
}

我的 tsconfig 是:

{
"compilerOptions": {
"target": "ES5",
"module": "commonjs",
"removeComments": true,
"noImplicitAny": false,
"preserveConstEnums": true,
"declaration": true,
"suppressImplicitAnyIndexErrors": true,
"outDir": "../js"
},
"filesGlob": [
"./**/*.ts",
"!./node_modules/**/*.ts"
]
}

当我的声明自动创建时,它看起来像这样:

export declare class HelloWorld {
greeting: string;
constructor(greeting: string);
}

但是当在其他项目中实际安装 npm 包时,这并不能很好地工作。当我导入包时,我必须使用:

import hello = require("hello-world/js/index");

(例如)

我发现当我将声明文件包装在模块中时 declare module "hello-world"{...} 然后我可以根据需要导入它 import hello = require("hello-world");

手动包装生成的定义文件不是一个选项,因为它始终会重写自身,是否有任何选项可以从 package.json 获取包名称并自动将定义包装在该模块中?

最佳答案

确保您在 package.json 中指定了 typings 属性...

{
"name": "hello-world",
"typings": "hello-world.d.ts",
...etc...
}

...或将定义文件更改为 index.d.ts

安装包含这些更改的软件包后,编译器将能够在您编写时解析它:

import hello = require("hello-world");

More details

关于node.js - 自动将 Typescript 定义文件包装到模块中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37751076/

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