Is it feasible to develop a TypeScript module in npm that serves as a dual-purpose tool, functioning as both a command line utility

My goal is to develop an npm TypeScript module that serves dual purposes - acting as a command line utility and exporting methods for use in other modules.

The issue arises when the module intended for use as a command line utility requires a node shebang (#!/usr/bin/env node) in the first line of index.ts. Importing this module into another one causes its code to start executing before any exported method is actually called. Here's an example:

#!/usr/bin/env node

const arg1: number = parseFloat(process.argv[2]);
const arg2: number = parseFloat(process.argv[3]);

console.log(superCalc(arg1, arg2)); // this gets called when superCalc() is referenced in another module

export function superCalc(arg1: number, arg2: number): number {
    return arg1 + arg2;
}

Answer №1

To streamline your code organization, consider placing the source code in a separate file that can be imported when needed. Here's an example of how you can structure your project:

src/index.ts

export function superCalc(arg1: number, arg2: number) : number {
    return arg1 + arg2;
}

src/cli.ts

#!/usr/bin/env node

const arg1: number = parseFloat(process.argv[2]);
const arg2: number = parseFloat(process.argv[3]);

console.log (superCalc(arg1, arg2));

package.json

{
  // Additional settings
  "bin": { "your-script": "./dist/cli.js" },
  "main": "dist/index.js",
}

By following this approach, users can easily run the CLI using npm run your-script, and also import functions from index.js by compiling TypeScript for distribution. For more guidance on creating CLIs with TypeScript, you can refer to this resource.

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

What could be causing my externally hosted React component to malfunction when being imported via NPM?

After successfully creating a standalone component within my original project, I decided to explore the possibility of releasing it as an NPM module. To kick off this process, I attempted to load the library from another repository using NPM in a new proje ...

Unable to resolve JSON parsing issue despite attempting multiple solutions. The npm registry error persists

Currently, I am a follower of This particular blog and have been attempting to set up yeoman by using the command: npm install -g yo However, I keep encountering the following error message: npm ERR! registry error parsing json I have made numerous atte ...

Using Webstorm with Node.js and npm test, the error message "'.'" is not a valid internal or external command is displayed

Recently delving into nodejs, I am utilizing Webstorm 9.0.1. In an attempt to incorporate Lab module for testing based on the guidelines provided in this tutorial: https://medium.com/the-spumko-suite/testing-hapi-services-with-lab-96ac463c490a Upon inspec ...

Encountering an unexpected termination error when using Typescript, pg, Express, and Psql within a Docker container: "Error: Connection terminated unexpectedly"

I am facing an issue with connecting to my database running on a Docker container using a postgres image: docker run --name postgres-container -p 2345:2345 -e POSTGRES_PASSWORD=password123 -e POSTGRES_USER=admin -d postgres The TypeScript code I have is i ...

When inserting a child element before the myArray.map(x => ) function, it results in rendering only a single child element from the array

Sorry for the confusion in my explanation, but I'm encountering an issue with displaying elements from an array. Here is the code snippet I am working on. Currently, the myArray contains 10 elements. When I place the <LeadingChild/> component ...

An error may occur when Typescript is instantiated with a varying subtype of constraint

I am encountering the "could be instantiated with a different subtype of constraint" error when trying to return a result that should match the expected type of a function. Despite removing irrelevant details, I'm struggling to pinpoint what exactly I ...

What methods are recommended for implementing changes in a TypeScript library throughout the development process?

When working on a TypeScript library that is utilized as a dependency by other libraries or applications, how can I efficiently handle frequent updates without going through the process of incrementing the version number, publishing it to an NPM registry, ...

An unfamiliar data type is provided as a number but is treated as a string that behaves like a number

Here is the code snippet in question: let myVar = unknown; myVar = 5; console.log((myVar as string) + 5); Upon running this code, it surprisingly outputs 10 instead of what I expected to be 55. Can someone help me understand why? ...

The variable type does not align with the export type

My TypeScript project includes a file that loads environment variables and exports them: const.ts: const { VARIABLE0, // type of VARIABLE0 is string | undefined VARIABLE1, } = process.env; if (!VARIABLE0 || !VARIABLE1) { throw new Error('Inval ...

Not all generic types specified with an extends clause are appropriately narrowed down as expected

Consider the following scenario: type MyType = 'val1' | 'val2' | 'val3'; const variable = 'val1' as MyType; const val2 = 'val2'; const val3 = 'val3'; declare function test<U extends MyType&g ...

What is the best way to collaborate and distribute local npm packages within a shared repository across different teams?

Unique Scenario Imagine the structure of a folder as follows: /my-app /src /dist /some-library /src /dist package.json my-package.json Two npm packages are present: one for my-app and one for some-library. my-app relies on some-library. ...

Using Angular 5 with Typescript to generate and return an array of freshly instantiated typed objects

My backend service provides me with "moments," and I have two functions to handle this data. One is a get() method that returns a single object, and the other is a search() method that returns an array of objects. moment.service.ts The get method success ...

The Angular component seems to be failing to refresh the user interface despite changes in value

Recently, I created a simple component that utilizes a variable to manage its state. The goal is to have the UI display different content based on changes in this variable. To test this functionality, I implemented the component and used a wait function to ...

Attempting to incorporate alert feedback into an Angular application

I am having trouble referencing the value entered in a popup input field for quantity. I have searched through the documentation but haven't found a solution yet. Below is the code snippet from my .ts file: async presentAlert() { const alert = awa ...

Exploring how to iterate through multiple arrays simultaneously in JavaScript

I have a specific problem with processing two sets of array objects to achieve a desired output. var parts={"Glenn": [12,22,32], "Ryan": [13,23,33], "Steve K": [14], "Jerom":[15,25,35], }; var labor={ "Glenn": [12,22,32], "Ryan": [13,23,33], "Steve K": [ ...

"Initiate React app with specific port number using the Command Line Interface

I'm trying to launch my react server on Linux CLI with a specific port number without modifying the package.json script. I want the ability to run multiple react instances on different ports via CLI. I've come across suggestions like npm start ...

Generating images with HTML canvas only occurs once before stopping

I successfully implemented an image generation button using Nextjs and the HTML canvas element. The functionality works almost flawlessly - when a user clicks the "Generate Image" button, it creates an image containing smaller images with labels underneath ...

Setting up a different version of Sails.js on your local machine

After successfully installing Sails.js version 0.9.13 globally on my Mac, I decided to experiment with the 0.10.0-rc4 version locally in a specific folder. Upon running sudo npm install sails@beta, everything seemed fine as the node_modules/package.json s ...

Learn the steps to establish a one-to-many relational record with the help of Node.js and Sequelize-Typescript

Currently, I am working on Nodejs with sequelize-typescript to develop a CRUD system for a one-to-many relationship. Unfortunately, I have encountered an issue with my code that I cannot seem to pinpoint. While I am able to retrieve records successfully us ...

Using npm link with git repositories that require SSH for access

I am currently in the process of developing a node application along with some necessary libraries. These projects are all housed in private repositories that can only be accessed through SSH. Unfortunately, using username and password authentication is no ...