![](/img/trans.png)
[英]Importing typescript definitions for my bundled javascript library
[英]Ambient Typescript Definitions Not Bundled in Library
我正在使用 TSDX 工具来构建一个 react-typescript 库。 我在我的@types/
目录中导出了许多类型,当我在应用程序中毫无问题地使用它们时,编译器清楚地选择了这些类型。
然而,在我的构建过程中,它们并没有被复制到我的 output 包中,这让我感到惊讶,因为它们是通过代码引用的(确实被正确地捆绑了)。
// tsconfig.json
{
"include": ["src", "types", "test"],
"compilerOptions": {
"target": "es5",
"module": "esnext",
"lib": ["dom", "esnext"],
"importHelpers": true,
"declaration": true,
"sourceMap": true,
"rootDir": "./",
"strict": true,
"noImplicitAny": false,
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictPropertyInitialization": true,
"noImplicitThis": true,
"alwaysStrict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": false,
"noFallthroughCasesInSwitch": true,
"moduleResolution": "node",
"baseUrl": "./",
"paths": {
"*": ["src/*", "node_modules/*"]
},
"jsx": "react",
"esModuleInterop": true
}
}
这实际上是设计使然,信不信由你。
您可以在 tsconfig.json 中定义类型的位置,并且预计它们总是在最终构建中(因为它们没有被移动)。 即给定这个结构:
src/app.ts
types/app.d.ts
Typescript 期望您发布的构建类似于:
build/app.js
build/app.d.ts
types/app.d.ts
为此,您可以在 tsconfig 中定义环境类型的路径
{
baseUrl: "./",
paths: [
"my-app": "./types/app.d.ts"
]
}
或添加一个包含目录中所有类型的 typeRoot,小心这一点,它将覆盖任何现有的 typeRoots,例如node_modules/@types
的那些,因此您需要重新声明它们。
{
typeRoots: ['./types', 'node_modules/@types']
}
如果您已声明路径,则使用my-app
的导入来使用类型。
预计您的最终构建将包含根目录中的types
目录,该目录在您的tsconfig.json
中定义。
我怀疑您将.d.ts
文件包含在您的应用程序源目录中,因此不希望它能够用于生产构建。 在这种情况下,您需要手动将其移动到构建中所需的位置,或者根据您的构建工具使用其他插件自动化它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.