微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何创建自定义 TypeScript 声明库并通过 NPM/Github 包将它们导入到我的项目中?

如何解决如何创建自定义 TypeScript 声明库并通过 NPM/Github 包将它们导入到我的项目中?

概述

我正在构建和发布一个在我的项目中使用的自定义 TypeScript 类型声明库。我在将 TypeScript 库导入我的项目时遇到问题。它导入,但我不断收到错误Module not found

我的尝试

  • 我已尝试修改 package.json
  • 我已尝试修改 tsonfig.json
  • 我已经从 type 导出了 interfacesrc/types/locationTypes.ts

src/types/locationTypes.ts

// TypeScript Type: Latitude
export type TLatitude = number;

// TypeScript Type: TLongitude
export type TLongitude = number;

// TypeScript Type: Coordinates
export interface ICoordinates {
  latitude: TLatitude;
  longitude: TLongitude;
}

src/index.ts

// Imports: TypeScript Types
import * as dateTypes from './types/dateTypes';
import * as locationTypes from './types/locationTypes';

// Exports
export {
  dateTypes,locationTypes,};

package.json

{
  "name": "@username/custom-types","version": "1.0.0","main": "./dist/index.ts","types": "./dist/index.d.ts","description": "","repository": {
    "type": "git","url": "git+https://github.com/username/custom-types.git"
  },"publishConfig": {
    "registry": "https://npm.pkg.github.com/username"
  },"author": "Jeff Lewis","license": "MIT","keywords": [
    "typescript","types","component-library",],"scripts": {
    "build": "cd src && tsc && cp ../package.json && Echo Build completed!","lint": "eslint . --ext .js,.jsx,.ts,.tsx"
  },"devDependencies": {
    "eslint": "^7.29.0","typescript": "^4.3.4"
  }
}

tsconfig.json

{
  "include": ["src/*"],// Specifies an array of filenames or patterns to include in the program
  "exclude": [                                                            // Specifies an array of filenames or patterns that should be skipped when resolving include. It is not a mechanism that prevents a file from being included in the codebase - it simply changes what the include setting finds.
    "**/__tests__/*","node_modules","babel.config.js","metro.config.js","jest.config.js","compilerOptions": {
    "module":  "ES6",// Sets the module system for the program. (https://www.typescriptlang.org/docs/handbook/modules.html)
    "outDir": "./dist",// If specified,.js (as well as .d.ts,.js.map,etc.) files will be emitted into this directory. The directory structure of the original source files is preserved
    "declaration": true,// Generate .d.ts files for every TypeScript or JavaScript file inside your project.
    "emitDeclarationOnly": true,// Only emit .d.ts files; Does not emit for .js files. (For TypeScript type deFinition libraries only?)
    "typeRoots": ["./node_modules/@types","./dist/index.d.ts"],// If typeRoots is specified,only packages under typeRoots will be included.
    "strict": true,// Enable all strict type-checking options.
    "strictFunctionTypes": true,// Enable strict checking of function types.
  }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。