Beginner's Guide: Building your debut JavaScript/TypeScript library on GitHub and npm

I am looking to develop a simple JavaScript/TypeScript library focused on color conversion. Some of the functions and types I aim to export include:

export type HEX = string;
export type RGB = { r: number; g: number; b: number };
export type RGBA = { r: number; g: number; b: number; a: number };
export type COLOR = HEX | RGB | RGBA;
// other types ...

export const hex2rgb = (hex: HEX): RGB => {
  const m = hex.match(/\w\w/g);
  if (m === null) throw new Error("");
  const [r, g, b] = m.map(x => parseInt(x, 16));
  return { r: r, g: g, b: b };
}

export const hex2rgba = (hex: HEX, alpha = 1): RGBA => {
  const [r, g, b] = hex.match(/\w\w/g).map(x => parseInt(x, 16));
  return { r: r, g: g, b: b, a: alpha };
};

// other functions...

I am planning to create a GitHub/Npm library for users to easily utilize these methods. However, I am unsure about how to proceed with structuring the project, folders, files, etc. This is my first time creating a library and any guidance would be appreciated. Despite not requiring React, I am currently using a Codesandbox in React for development.


The proposed structure of my code could be as follows:

project
|_ src
   |_ index.ts contains all functions
   |_ types.ts includes types
|_ test includes test code

What steps should I take next? Do I need to create a package.js? Can I integrate libraries like Lodash?

Answer №2

If you're feeling stuck, consider checking out the npm documentation first. Here are some general steps to follow:

  • Begin by creating a package.json file.
  • Next, create the necessary file that will be loaded when your module is required by another application.

  • Don't forget to thoroughly test your module before finalizing it.

For a more detailed explanation, make sure to visit this link.

Answer №3

Sharing your library with the world involves a series of steps, each crucial to ensuring its success. The entire development process is influenced by various factors like dependencies, testing platforms, and the versions of JS/Typescript you're using.

If you're looking for a comprehensive guide on navigating the development life cycle and publishing on npm, check out this helpful tutorial:

Once your code has been rigorously tested, it's time to make it public.

Start by creating an account on npmjs.com. Then, execute the following command from your terminal:

npm login

Enter your login credentials as prompted. This will save your details for future use, eliminating the need to re-enter them every time you publish.

To officially publish your package, run:

npm publish

By doing this, your package will be added to the NPM registry. Once the publishing process is complete (usually in less than a minute), you can view your package at the following link: https://www.npmjs.com/~{username}/{package-name}.

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

Verify the type of email domain (personal or corporate)

Here's an example: isPersonalEmail("<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c0aea1ada580a7ada1a9aceea3afad">[email protected]</a>") // true isPersonalEmail("<a href="/cdn-cgi/l/email- ...

Dealing with event delegation on elements that are not nested

Working with Bootstrap group radio buttons where I need to implement event delegation. <div class="btn-group" role="group" aria-label="Basic radio toggle button group"> <input type="radio" class="btn- ...

Tips on preventing duplication of APIs when retrieving data using nextjs

In my code, I have a function that can be called either from server-side rendering or client side: export const getData = async (): Promise<any> => { const response = await fetch(`/data`, { method: 'GET', headers: CONTENT_TYPE_ ...

Show information - press the button on the current PHP page

After successfully reading files via PHP from a directory and dynamically creating a drop-down menu to view the file content, I have a query. Is there a way to display the text files' content on the same page without calling another PHP page? I know t ...

Complete a form on an external website using either C# or Javascript

I am looking for a solution to automatically fill and submit a form from a specific URL, as I need to trigger this process from my domoticz. Despite attempting different methods like using AJAX or injecting JavaScript, I keep encountering issues with the S ...

Utilizing Vue's data variables to effectively link with methods and offer seamless functionality

I am encountering difficulty retrieving values from methods and parsing them to provide. How can I address this issue? methods: { onClickCategory: (value) => { return (this.catId = value); }, }, provide() { return { categor ...

The Problem of Restoring Column Height in Tabulator 4.6.3 Filters

The Issue After activating and deactivating header filters, the column height does not return to its original state. Is this the expected behavior? Is there a way to reset the column height? Check out this JS Fiddle example: https://jsfiddle.net/birukt ...

Adding custom TypeScript classes to an Electron project is a straightforward process that allows developers to enhance their

Currently working on a hello world project in Electron and stumbled across the possibility of using Typescript for the Main process, . The provided instructions suggest changing the file extension from index.js to index.ts and updating the package.json fi ...

creating a div that functions similarly to a radio button

Is it possible to create a div that mimics the behavior of a radio button? I'm looking for a solution that doesn't involve jquery, as many people have recommended. After doing some research, I found a few potential options. In the past, I'v ...

How to customize XMLHttpRequest in Firefox's WebExtension

Recently, I've been attempting to override the XMLHttpRequest.protype.open method within Firefox's WebExtension environment. My current approach involves the following code snippet written in a content script: var oldOpen = XMLHttpRequest.protot ...

What is the approach to forming a Promise in TypeScript by employing a union type?

Thank you in advance for your help. I am new to TypeScript and I have encountered an issue with a piece of code. I am attempting to wrap a union type into a Promise and return it, but I am unsure how to do it correctly. export interface Bar { foo: number ...

Pause the for loop until all nested asynchronous database calls are completed

Currently, I am utilizing the listCollection method within mongodb to loop through each collection that is returned using a query with find. The issue arises when I attempt to construct an object within the loop that I intend to return with response.json ...

Utilizing JavaScript to Invoke Controller Actions

Currently, my ASP.NET MVC actions return JSON data, which is then displayed on the screen by my client using jQuery's ajax function. The JavaScript code I use to call these controller actions includes absolute paths like this: $.ajax({ url: &apos ...

Attempting to start and restart an asynchronous function using setIntervalAsync results in a TypeError because undefined or null cannot be converted to an

Recently, I've been working on creating a web scraper that utilizes data extracted from MongoDB to generate an array of URLs for periodic scraping using puppeteer. My goal is to make the scraper function run periodically with the help of setIntervalAs ...

Integrate React tags with Redux form to ensure the values are transmitted as an array within the payload

I am currently working on a redux-form that contains a component for tags. I am struggling to figure out how to retrieve the tag values in an array as a payload. Any help would be greatly appreciated. Below is the code snippet for the tags component: ...

Is there any trouble with this controller method?

Every time I use routers without controllers, they work perfectly fine. But the moment I add controllers to them, my routers stop working completely. Can someone please shed some light on what might be causing this issue with my router functions? LOGIN CO ...

if and elsif JSON with Angular

Currently, I am working on completing a task within our project. To provide more context, I have a field with items that I must select. Once I choose an item, another field appears in which I must select additional elements. These elements need to be sen ...

Accessing specific values from a JSON object in JavaScript

I'm fairly new to JSON and have a JSON String that I'd like to access and print to a DIV. I've managed to get it working using the following code snippet: document.getElementById("product_content").innerHTML=javascript_array[5].name; The s ...

Apply SetTimeout exclusively for desktop devices

A website I'm working on has a background video from YouTube using YTPlayer. To enhance the user experience, I have implemented a CSS spinner that displays while the page is loading. However, I noticed that the spinner disappears before the video fini ...

Using async/await in a for loop | The await keyword can only be used inside an asynchronous function

I've been attempting to execute the following code: async function verifyExistingUsers(db, users) { return new Promise((resolve, reject) => { var companies = [] for (const [index, user] of users.entries()) { let comp ...