鉴于这两个打字稿文件
api/Token.ts
interface Token {
code: string
}
export default Token
和 index.ts
export * from './api/Token'
带有--declarations
开关的 tsc 1.5将生成两个.d.ts
个文件(内容相似)
api/Token.d.ts
interface Token {
code: string;
}
export default Token;
和 index.d.ts
export * from './api/Token';
使用以下选项
运行 grunt-dts-bundle dts_bundle: {
release: {
options: {
name: 'my-module',
main: 'index.d.ts'
}
}
}
将生成具有以下内容的环境模块声明文件my-module.d.ts
declare module 'my-module' {
export * from './api/Token';
}
但是由于:Import or export declaration in an ambient module declaration cannot reference module through relative module name.
我如何自动为上面的两个打字稿文件生成环境模块声明?
修改
的最新动态答案 0 :(得分:3)
我最近写了blog post这个。总而言之,如果您将index.ts
替换为api.ts
,则可以使用autodts,其中包含以下内容:
export {default as Token} from './api/Token';
确保api.ts
与api
目录位于同一位置(旁边,不在其中)。
然后你需要一个package.json
文件:
{
"name": "api",
"version": "1.0.0",
"main": "dist/api.js",
"scripts": {
"preinstall": "npm install autodts",
"postinstall": "autodts link",
"prepublish": "tsc && autodts generate"
},
"typescript": {
"definition": "index.d.ts"
},
"dependencies": {
"autodts": "~0.0.4"
},
"devDependencies": {
"@lib/autodts-generator": "~0.0.1",
"typescript": "~1.5.3"
}
}
包名api
与文件api.ts
和目录api
匹配非常重要。这样,Node.js和TypeScript编译器在使用您的包时都会在相同的位置查找。
最后,您需要一个tsconfig.json
文件:
{
"compilerOptions": {
"declaration": true,
"module": "CommonJS",
"target": "es5",
"outDir": "dist"
},
"files": [
"api.ts"
]
}
现在npm install
将编译您的包并生成index.d.ts
中definition
设置中定义的捆绑package.json
文件。
要使用您的包,您可以执行以下操作:
/// <reference path = "api/index.d.ts" />
import {Token} from 'api';
class foo {
key: Token;
}
您可以使用autodts link
使reference path
保持最新状态,查看博客文章和/或autodts文档。
结果index.d.ts
包含:
/// <reference path="index.ref.d.ts" />
declare module 'api/Token' {
interface Token {
code: string;
}
export default Token;
}
declare module 'api' {
export { default as Token } from 'api/Token';
}
index.ref.d.ts
和api.js
是空白的。