我最近写了一个博客文章 http://blog.charto.net/node/Publishing-TypeScript-based-modules-on-npm/对这个。总而言之,您可以使用autodts https://www.npmjs.com/package/autodts如果你更换index.ts
with api.ts
,包含以下内容:
export {default as Token} from './api/Token';
确保api.ts
与api
目录(在它旁边,而不是在它里面)。
那么你需要一个package.json
file:
{
"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
file:
{
"compilerOptions": {
"declaration": true,
"module": "CommonJS",
"target": "es5",
"outDir": "dist"
},
"files": [
"api.ts"
]
}
Now 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
and api.js
是空白的。