Developing a TypeScript library through modular class implementation

I have developed a Web API and now I want to streamline my code by creating a library that can be reused in any new project I create that interacts with this API.

My goal is to organize my code efficiently, so I plan to have separate classes for each endpoint structure. For example, if I have multiple User endpoints such as Register and Login, I would consolidate them into a single UserClient class offering both methods:

export default class UserClient
{
    register(email: string, password: string)
    {
        // implementation here
    }

    login(email: string, password: string, remember: bool)
    {
        // implementation here
    }
}

Here's how I structured my code:

package.json
tsconfig.json
--src
----api
------user-client.ts
----models
------user
--------logindata.ts

My tsconfig.json contains the following configurations:

{
  "compilerOptions": {
    "declaration": true,
    ...
}

I also have a package.json file specifying details about the library:

{
  "name": "xxx",
  "version": "1.0.0",
  ...
}

As I continue developing my library, I came across several questions:

  • Do I need an index.ts file in src? If yes, what should be included in it?
  • Should I change the types field to something else in package.json?

Ultimately, my aim is to ensure typings exist for every class within the library so that they can be imported and used seamlessly in other projects like this:

import {UserClient} from "myLib"
import {BooksClient} from "myLib"

However, when I compile the library using tsc, it does not generate an index.d.ts file (due to the absence of an index.ts) and places the user-client.js and user-client.d.ts directly in the dist folder without maintaining the existing structure. This impedes their usage in other libraries.

Answer №1

Alright, I managed to fix the issue. The first step is to ensure that the client is exported properly.

Thus, your user-client.ts file should resemble the following:

export class UserClient
{
    // code
}

Next, in your index.ts file, make sure to EXPORT instead of import the client like so:

export {UserClient} from "./api/user-client"

After building the files with the tsc command, you can link them in your consuming library using npm link ../jsapi. Then, you can easily import the client with:

import {UserClient} from 'jsapi'

I found a helpful tutorial at , but ultimately had to refer to their actual code at https://github.com/bersling/typescript-library-starter/blob/master/library-starter/src/index.ts for the correct solution.

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

Unnecessarily intricate: A Comparison and Enumeration of Elements in Arrays

I am facing a challenge with organizing arrays that represent categories and subjects. Each array represents a category, while each item within the array is a subject. For example: 4 Categories with Subjects ['A','B','D'] [&a ...

Unusual glitch involving onChange method in React JS

Encountered a peculiar bug with an autocomplete form. I implemented an onChange function for the form that can access two arguments, the "event" and the "value". The function is structured like this: handleChange(event, value){ const newElement = ...

Leave a message | Google Sheets | JavaScript using nodeJS

I am having trouble adding comments to cells using the "Google Spread-Sheet" module in NODEJS. I have successfully written to cells, read from them, and deleted them, but I can't figure out how to add a comment to a cell. The tutorials I have found on ...

Using a variable to contain a loop in Jquery

Seeking assistance with a jQuery function that retrieves values from a PHP form to create a variable for an ajax call. Is it possible to include a loop within a variable? Below is a snippet of my code to provide better context: ... var teacher_ids = $( & ...

Creating a Javascript function to turn lights off using CSS manipulation, similar to the feature found

Is there a way to use JavaScript to obscure all elements on a page except for one specific HTML element? This web application is optimized for Chrome, so CSS3 can also be utilized. ...

How to use getBoundingClientRect in React Odometer with React Visibility Sensor?

I need help troubleshooting an error I'm encountering while trying to implement react-odometer js with react-visibility-sensor in next js. Can anyone provide guidance on how to resolve this issue? Here is the code snippet causing the problem: https:/ ...

Sequelize: Establishing association upon saving without the need to retrieve another object

Suppose I have two tables, parent and child, where the parent has multiple children. They are properly mapped in Sequelize. Now, I need to add a new child to an existing parent. However, I do not have access to the parent instance, only its id. I am aw ...

Updating default values in reactive() functions in Vue 3: A step-by-step guide

Currently, I am in the process of developing an application using Nuxt 3 and implementing the Composition API for handling async data. The specific scenario I am facing is this: I have a page that displays articles fetched from the database using useLazyFe ...

Determine if a mobile application has been installed using Vue.js

I am currently developing a web application and have implemented a check to determine whether the user is accessing it from a mobile device or laptop. Let's consider the link as: my-site.com In addition to the web version, my site also offers a mobi ...

There was an issue stating that valLists is not defined when paginating table rows with AngularJS and AJAX

I found a helpful code snippet on this website for implementing pagination in AngularJS. I'm trying to adapt it to work with data from a MySQL DB table called 'user', but I keep running into an issue where the valLists variable is undefined, ...

Refreshing Angular 4 route upon modification of path parameter

I have been struggling to make the subscribe function for the params observable work in my Angular project. While I have successfully implemented router.events, I can't seem to get the subscription for params observable working. Can anyone point out w ...

Using jQuery and AJAX to send a post request in a Razor page and automatically redirect to the view returned by a MVC Action (similar to submitting

I send a json array to the MVC Action using either JQuery or Ajax, and the Action processes the request correctly. However, when the MVC Action returns a View, I am unsure of how to redirect to this View or replace the body with it. Overall, everything se ...

"JavaScript encountered an Uncaught TypeError: Cannot read property 'style' of undefined

Looking to create a local time clock using HTML, here is the code: <body> <div class="container text-center"> <div class="row"> <div class="col-xs-12 col-sm-6"> & ...

What is the reason for the truth value of `type a = {} extends {a?:number}? true:false;`?

Why is type a = {} extends {a?:number}? true:false; evaluated as true, while type b = {a?:number} extends {}? true:false; is also true! It seems like the empty object {} acts as a supertype that can extend other types. This raises some questions about ...

Alternative for document.ready in AngularJS when outside of AngularJS

I am currently developing a small Chrome extension that will interact with an Angular website. I have managed to successfully detect full page reloads using $(document).ready(), but I am facing issues when it comes to detecting page changes triggered by ng ...

What methods can be used to assess the security risks posed by a third-party library implemented in a React JS application?

How can I ensure the security of third-party libraries added to my create-react-app with additional scripts? ...

The relentless Livewire Event Listener in JavaScript keeps on running without pausing

I need to create a solution where JavaScript listens for an event emitted by Livewire and performs a specific action. Currently, the JavaScript code is able to listen to the Livewire event, but it keeps executing continuously instead of just once per event ...

Is there a way to track when the Angular DTOptionsBuilder ajax call is complete and trigger a callback function?

Working with angular datatables, I have the following code: beforeSend:</p> success callback causes the table on the page not to populate with the data. How can I implement a callback that triggers once the ajax is done without interfering with the ...

Trigger an alert using the Ajax response

Is there a way to display the value of imageX outside of the $.ajax() function? var imageX; $.ajax({ type: 'GET', url: 'php/my1.php', dataType: 'json', async: 'false', success: function(response) ...

What is the best way to design a basic server component that has the ability to retrieve data in NextJS 13?

Exploring the world of NextJS, I am currently utilizing NextJS 13 with the new app directory instead of the traditional pages directory structure. Despite trying various methods to fetch data, none seem to be working as expected. The process should be stra ...