Issue with module not found error while importing TypeScript library

In my TypeScript library, I have created models and API calls for multiple web applications that share the same backend.

My goal is to export these models and functions in modules so that consumer apps can import them like this:

import { SomeType, SomeFunction } from 'myLib/myModule';

Although it currently works well, I am encountering the following TSError: TS2307: Cannot find module 'myLib/myModule' or its corresponding type declarations.

The library is built using Vite and is used in consumer apps as a .tgz file.

This is the file architecture of the library. The index.ts files in api/ and computation/ directories are exporting all the models and services contained in the subdirectories:

https://i.sstatic.net/RpCTG.png

The index.ts file located in src/ does the following:

export * from './api';
export * from './computation';

The init.ts file simply exports a function to initialize the library.

I also have the following configuration files:

{
  "compilerOptions": {
    "module": "es2015",
    "target": "es2015",
    "declaration": true,
    "outDir": "./dist",
    "rootDir": "./src",
    "moduleResolution": "node",
    "esModuleInterop": true,
  },
  "include": [
    "src/**/*"
  ]
}

package.json:

{
  "name": "coanda-sdk-ts",
  "version": "1.0.0",
  "files": ["dist"],
  "main": "./dist/coanda-sdk-ts.cjs.js",
  "module": "./dist/coanda-sdk-ts.es.js",
  "types": "./dist/index.d.ts",
  "exports": {
    ".": {
      "import": "./dist/coanda-sdk-ts.es.js",
      "require": "./dist/coanda-sdk-ts.cjs.js",
      "types": "./dist/index.d.ts"
    },
    "./api": {
      "import": "./dist/api/index.js",
      "require": "./dist/api/index.js",
      "types": "./dist/api/index.d.ts"
    },
    "./computation": {
      "import": "./dist/computation/index.js",
      "require": "./dist/computation/index.js",
      "types": "./dist/computation/index.d.ts"
    },
    "./init": {
      "import": "./dist/init.js",
      "require": "./dist/init.js",
      "types": "./dist/init.d.ts"
    }
  },
  "scripts": {
    "build": "vite build && tsc --project tsconfig.json"
  },
  "dependencies": {
    "axios": "^1.4.0"
  },
  "devDependencies": {
    "@types/node": "^20.3.2",
    "vite": "^4.3.9"
  }
}

vite.config.js:

const path = require('path');
const { defineConfig } = require('vite');

module.exports = defineConfig({
  resolve: {},
  build: {
    lib: {
      entry: {
        api: path.resolve(__dirname, 'src/api/index.ts'),
        computation: path.resolve(__dirname, 'src/computation/index.ts'),
        init: path.resolve(__dirname, 'src/init.ts')
      },
      name: 'coanda-sdk-ts',
      fileName: (format) => `coanda-sdk-ts.${format}.js`,
    },
    rollupOptions: {},
  },
});

The dist/ folder after building the library looks like this: https://i.sstatic.net/ggmzg.png

These files seem to be related to my issue, which seems unusual:

src/coanda-sdk-ts.cjs.js
src/coanda-sdk-ts.cjs2.js
src/coanda-sdk-ts.cjs3.js
src/coanda-sdk-ts.es.js
src/coanda-sdk-ts.es2.js
src/coanda-sdk-ts.es3.js

I have attempted various solutions to eliminate the TSError, but it appears that my configurations may no longer be applicable. Unfortunately, I am unable to identify the problem. The consumer app is functioning correctly and utilizing the library's functions by importing modules as follows:

import { SomeAPIFunction } from 'coanda-sdk-ts/api';

If possible, I would prefer not to make any changes to this setup. Can someone please offer assistance?

Answer №1

After experimenting with various solutions, including removing an unnecessary tool like Vite, my supervisor provided the answer to my dilemma. I wanted to share it in case others were facing a similar issue.

To resolve the problem, I had to make some changes in my library's package.json file:

 "typesVersions": {
    "*": {
      "api": [ "./dist/api/index.d.ts" ],
      "computation": [ "./dist/computation/index.d.ts" ],
      "init": [ "./dist/init.d.ts" ]
    }
  }

With these adjustments, the imports are now resolving correctly without any TypeScript errors. Thank you for taking the time to read this!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Obtain the outcome of HTML5 FileReader by utilizing promises within an asynchronous function

I am encountering a challenge in my Angular 4 application where I am working with an image. I am trying to pass the base64 string to another variable, but due to the asynchronous nature of this process, the image.src ends up being empty. As a result, the ...

Failure in SystemJS during ahead-of-time compilation due to missing NgZone provider

Previously, I have successfully used Angular's ahead-of-time compilation. However, after adding routing and lazy loading to my app, I am facing difficulties in making it work again. Upon updating my code to the latest 2.0 release, it functions well w ...

Implementing individual NGRX Selectors for each child component to enable independent firing

My component serves as a widget on a dashboard, and I am using *ngFor to render multiple widgets based on the dashboard's data. Each WidgetComponent receives some of its data via @Input() from the parent. parent <app-widget *ngFor="let widget ...

Typically used to describe an item with a variable amount of string attributes

I have a TypeScript generic for an object with an unspecified number of string parameters like this: type Params<T extends string[]> = Record<T[number], string>; However, every time I want to use it, I need to define it with an array like so: ...

Determining the total number of items in an array in Angular efficiently without causing any lag

Currently, I am using the function checkDevice(obj) to validate if a value is present or not. In addition to this functionality, I also require a separate method to determine the number of occurrences of Device in the Array. component.ts public checkDevi ...

Preventing Undefined Values in RxJS Observables: A Guide

I am facing an issue with passing the result of a GET request from Observable to Observer. The problem lies in the fact that the value becomes undefined because it communicates with the observer before the GET execution finishes. observer:Observer<a ...

The datepicker within the dialog box is obstructed

There seems to be an issue that I'm encountering: https://i.sstatic.net/7aFqA.png Whenever I click on the datepicker input, the calendar appears overlapped. This is evident because when I hide the dialog, the calendar displays correctly: https://i. ...

Exploring the Worldwide Influence of TypeScript, React, and Material-UI

I am currently following an official tutorial on creating a global theme for my app. In my root component, I am setting up the global theme like this: const themeInstance = { backgroundColor: 'cadetblue' } render ( <ThemeProvider theme ...

Encountering type errors in NextJS with TypeScript

I am facing an issue while trying to run this function: "use server"; export const addProduct = async (formData: FormData, imageUrl: string) => { const productName = formData.get("productName")?.toString(); const description = f ...

A guide on manipulating queryParams within the current route in angular 2 without triggering a page reload

I am currently dealing with the following route: http://localhost:96/#/pages/settings/devices I am looking to add queryParams={name:realTime} to this existing route, like so: http://localhost:96/#/pages/settings/devices?name=realTime Can I manipulate ...

Difficulty with Angular's Interpolation and incorporating elements

I've encountered an issue with String Interpolation while following an Angular course. In my server.component.ts file, I've implemented the same code as shown by the teacher in the course: import { Component } from "@angular/core"; @Component ( ...

`It is important to note that in Tailwind CSS, `h-8` does not supersede `h-4

I developed an Icon component that looks like this: import { IconProp, library } from "@fortawesome/fontawesome-svg-core"; import { far } from "@fortawesome/free-regular-svg-icons"; import { fas } from "@fortawesome/free-solid-svg- ...

Wildcard routes taking precedence over other defined routes

Currently, I'm developing a Node.js server utilizing Express.js and Typescript. Within my project structure, there is a folder named "routes" where I store .ts files containing route definitions. An example of a route file might appear like this: impo ...

Exploring the World of JSON Mapping Libraries

In my project, I am dealing with objects (like a ball) that have specific data members and functions. These objects are being retrieved from various servers, each with its own hierarchy. For example: class Ball { int size; string color; } An instance ...

Using TypeScript 3.0 alongside React defaultProps

If I define a prop in the following way: interface Props { Layout?: LayoutComponent; } Then, if I set defaultProps on a ClassComponent: class MyComp extends React.Component<Props> { static defaultProps: Pick<Props, 'Layout'> = ...

How can we use tsyringe (a dependency injection library) to resolve classes with dependencies?

I seem to be struggling with understanding how TSyringe handles classes with dependencies. To illustrate my issue, I have created a simple example. In my index.tsx file, following the documentation, I import reflect-metadata. When injecting a singleton cl ...

Create a nested array of subcategories within an array object

Currently, I am working on integrating Django Rest and Angular. The JSON array received from the server includes category and subcategory values. My goal is to organize the data such that each category has its related subcategories stored as an array withi ...

Error in Typescript: The type 'string' cannot be assigned to the type '"allName" | `allName.${number}.nestedArray`' within the react hook form

Currently, I am tackling the react hook form with typescript and facing a challenge with my data structure which involves arrays within an array. To address this, I decided to implement the useFieldArray functionality. allName: [ { name: "us ...

Avoiding the pitfalls of hierarchical dependency injection in Angular 6

Too long; didn't read: How can I ensure that Angular uses the standard implementation of HttpClient in lower level modules instead of injecting a custom one with interceptors? I have developed an Angular 6 library using Angular CLI. This library expo ...

Objects in the array are failing to sort in the expected sequence

I am facing an issue with sorting an array of objects by a date property using the lodash function orderBy. I have tried to sort it in both ascending and descending order. var searchObj = [{id: 1, postDate: '2/24/2016 5:08 PM'}, ...