npm如何发布打字稿界面定义

时间:2020-01-14 22:29:57

标签: typescript npm typescript-definitions

在过去的3-4天里,我一直在试图解决这个问题,在谷歌上搜索了很多东西,但是我看不到任何包含用例的示例。我想npm publish一个包含其类型定义的库。

我真的开始做TS了,因为另一个团队需要我的图书馆来支持打字。

所以,让我尝试尽可能多地(和尽可能少)细节:

tsconfig.json:

{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "allowUmdGlobalAccess": true,
    "baseUrl": ".",
    "declaration": true,
    "declarationMap": true,
    "forceConsistentCasingInFileNames": true,
    "jsx": "react",
    "module": "commonjs",
    "noImplicitAny": true,
    "noUnusedParameters": true,
    "noUnusedLocals": true,
    "outDir": "./dist/",
    "paths": {
    },
    "sourceMap": true,
    "strict": true,
    "target": "es6",
  },
  "include": [
    "./src"
  ]
}

package.json:

  "main": "dist/index.js",
  "scripts": {
    "tsc": "tsc",
    "prepack": "npm run clean && npm run tsc",
  },
  "types": "./dist/index.d.ts",

src / index.ts(内置在dist / index.js + dist / index.d.ts中):

export { IAction, IState } from './types';

src / types(内置于dist / types.js + dist / types.d.ts中):

import { Map } from 'immutable';

export interface IAction {
  type: string;
  payload: object;
}

export interface IState extends Map<string, Map<string, any>> {
}

此存储库中还有其他代码可以毫无问题地使用它们。 tsc不会抱怨并进行构建。

现在,我在另一个项目中执行npm packnpm install ../path/to/my/file-0.0.1.tgz。然后,当我想使用我的界面(在这种情况下,是redux reducer)时:

import { IAction, IState } from 'my-lib';  // <-- match my package.json name

const reducer = (state: IState, action: IAction) => {
  ...
}

我收到以下错误:

error TS2709: Cannot use namespace 'IState' as a type.
error TS2709: Cannot use namespace 'IAction' as a type.

我真的不知道为什么会这样。为了建立定义文件,我还需要执行另一步骤吗?理想情况下,我希望不必手动构建它。

让我知道是否需要提供更多详细信息。

感谢您的帮助和耐心阅读。

1 个答案:

答案 0 :(得分:0)

您需要在package.json中包含以下内容

  ...
  "main": "dist/index.js",
  "typings": "dist/index.d.ts",
  "source": "lib/index.ts",
  "files": [
    "dist",
    "lib"
  ],
  ...
相关问题