NPM自定义包:编译和导出TypeScript接口

wgx48brx  于 2023-10-19  发布在  TypeScript
关注(0)|答案(1)|浏览(213)

提问:我是否缺少了一些TS配置或TS构建步骤?

我创建了一个新的npm包:

Custom-NPM-Package /

  • src
    简体中文
    -- index.d.ts
    -- IType.ts
    使用tsconfig.json:
{
  "compilerOptions": {
    "target": "es5",
    "module": "CommonJS", 
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": false,
    "declaration": true,
    "declarationDir": "./dist",
    "esModuleInterop": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "react",

    "outDir": "./dist", 
    "rootDir": "./src", 
    "allowSyntheticDefaultImports": true, 
  },
  "include": [
    "./src/**/*.ts", 
    "./src/**/*.tsx", 
    "./src/**/*.jsx" 
  ],
  "exclude": [
    "node_modules", 
    "dist"
  ]
}

目标是从其他项目(React)导入类型,
1.安装软件包:
npm install Custom-NPM-Package
1.导入TS类型:
从“Custom-NPM-Package”导入{ IType }
但我犯了个错误
./node_modules/Custom-NPM-Package/dist/index.js export“IType”(重新导出为“IType”)未在“./IType”中找到(可能的导出:IT类型,__esModule)

bwitn5fc

bwitn5fc1#

我终于在这里找到了解决办法:
How to create npm package with definition files?
1.在 * tsconfig.json * 中将“declaration”设置为true。这告诉TypeScript生成**.d.ts*
1.在 package.json 中设置“types”。这告诉TypeScript在哪里找到生成的 *.d.ts文件。

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "strict": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "declaration": true  <--
  }
}

package.json

{
  "name": "my-package",
  "version": "1.0.0",
  "main": "index.js",
  "types": "index.d.ts", <--
  "license": "ISC",
  "devDependencies": {
    "typescript": "^3.8.3"
  }
}

如果您有多个ts接口,请注意:

  • src

-- componentA/类型/
-- componentA/Types/InterfacesA.TS
-- componentB/类型/
--组件B/类型/接口B.TS
您可以在src中创建另一个文件夹(类型为多个):

  • src

-- src/types
并在里面创建一个 index.ts 文件;导入类型并导出它们:

index.ts

import { IIntefacesA } from './componentA/Types/IntefacesA';
import { IIntefacesB } from './componentA/Types/IntefacesB';

export type { IIntefacesA, IIntefacesB };

然后从src/index.d.tsindex.js 指向这个文件夹:

index.d.ts/index.js

export * from './ReactComponent1';
export * from './ReactComponentX';
export * from './types';

相关问题