问题:
任何在许多不同文件中重用大量类型的项目都可以使用在脚本文件 中定义的类型。这些类型在项目中全局可见,不需要导入,请参阅 the official handbook :
In TypeScript, just as in ECMAScript 2015, any file containing a top-level
import
orexport
is considered a module. Conversely, a file without any top-levelimport
orexport
declarations is treated as a script whose contents are available in the global scope (and therefore to modules as well).
我在我的项目中使用了这些全局类型,它们运行良好。但后来我决定把这个项目变成一个 NPM 模块。该模块的“全局”类型应该只对模块本身可见。
首先我按原样发布了模块,没有添加任何 <reference/>
s 和 typeRoots
.但是,当将模块导入到不同的项目时,TypeScript 无法找到全局类型并且无法编译。
然后我添加了<reference path="types.ts" />
到使用全局类型的模块中的所有文件,然后我再次推送。令我惊讶的是,这使得类型不仅可用于模块,而且可用于使用它的整个项目,从而导致本地类型与模块类型之间发生冲突。
(请注意,我发布的模块的两个版本都可以完全自行编译,当我在不同的项目中使用 npm i
安装模块时,问题就开始了。)
有没有办法让模块的“全局”类型只在模块中可用?
我的模块结构:
.
├── dist
│ ├── index.d.ts
│ ├── index.js
│ ├── foo.d.ts
│ ├── foo.js
│ ├── types.d.ts
│ └── types.js
├── package.json
├── src
│ ├── index.ts ← contains import/export
│ ├── foo.ts ← contains import/export
│ └── types.ts ← contains only types, no import/export
└── tsconfig.json
第一次发布,index.ts
和 foo.ts
仅包含常规代码 - 导致类型在项目时无法识别。当我第二次发布模块时,我添加了 ///<reference path="types.ts"/>
到两个index.ts
和 foo.ts
.这被翻译成 path="types.d.ts"
在编译文件中 index.d.ts
和 foo.d.ts
.
package.json:
{
"name": "@foo/foo",
"version": "1.0.0",
"main": "dist/index.js"
}
tsconfig.json:
{
"include": ["./src"],
"compilerOptions": {
"moduleResolution": "classic",
"outDir": "./dist",
"module": "commonjs",
"declaration": true
}
}
最佳答案
如果依赖项需要某些类型,我觉得消费者也应该获得这些类型,因此实现这一点可能并不容易。
你可以尝试在一个单独的库中定义你的全局类型(引用你的 previous question 了解如何做到这一点;这次库可以像 my-global-library/index.d.ts 这样简单
,除非您需要从同级依赖项中导入类型——在这种情况下,您可以考虑将它们分离到它们自己的共享库中),然后将该库安装为 NPM 的 devDependency
包裹。任何使用您的 NPM 包的项目都不会安装 devDependency
。
关于typescript - 如何制作一个使用全局类型但不扩充使用它的项目的 NPM 包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55713045/