Building package dependencies for TypeScript bundled projects: a comprehensive guide

Currently, I am developing a TypeScript module that relies on another TypeScript-based project called winston.

The types for winston are bundled in an index.d.ts file, and there is no @types/winston package available as a "devDependency".

From what I gather, the typescript dependency should be under devDependencies since it is not needed at runtime. On the other hand, winston should be in the dependencies section as it will be used during runtime.

However, when I run npm install --only=dev, the winston package is not installed. This leads to compilation errors with tsc due to missing types (

error TS2307: Cannot find module 'winston'
).

Even if I manage to workaround this issue, it's evident that I cannot access the typings of the package during TypeScript compilation because they were not downloaded.

So, what is the recommended approach here? Should every TypeScript-bundled package providing its own types be placed in the devDependencies section of package.json? But then, what about npm install --production which would skip this dependency and cause runtime failures?

I experimented by adding winston to both devDependencies and dependencies in package.json. However, running npm install --only=dev does not download packages listed under dependencies (not sure if intended or a bug in npm).

package.json

{
  "name": "tst",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/node": "^12.7.4",
    "typescript": "^3.6.2"
  },
  "dependencies": {
    "winston": "^3.2.1"
  }
}

test.ts

import * as winston from "winston";

const logger = winston.someMethod();

Answer №1

Most developers are familiar with the command npm install. However, when you add the parameter --only=dev, NPM will only download packages listed under devDependencies.

It's important to note that this parameter is not meant for distinguishing between development and production builds. Using it incorrectly can lead to errors.

When creating a TypeScript library, there is no need to rely on external type definitions from @types. Instead, include your own type definitions within the package itself:

Make sure that TypeScript generates definition files in your output folder by checking for .d.ts files alongside the generated .js files. If they're not present, consult the tsconfig.json file to configure TypeScript to emit definitions.

In the package.json file, specify the “main” property as the entry point for the compiled .js package, and add a “types” property pointing to the corresponding .d.ts file with the same name.

Following these steps should help you set up your project successfully if you haven't already done so.

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

the process of accessing information from a service in an Angular Typescript file

After making a POST request using Angular's HTTP client, the response data can be accessed within the service. However, is there a way to access this data in the app.component.ts file? I am able to retrieve the response data within the service, but I ...

Error message encountered during angular project build using ng build: angular.json file missing

I had successfully created a project on my laptop a month ago and didn't encounter any errors. However, when I cloned the repository to a new computer today, I encountered some issues. After running 'npm i' to install packages, I attempted t ...

How can we leverage mapped types in TypeScript to eliminate properties and promisify methods?

Below is the provided code snippet: class A { x = 0; y = 0; visible = false; render() { return 1; } } type RemoveProperties<T> = { readonly [P in keyof T]: T[P] extends Function ? T[P] : never//; }; type JustMethodKe ...

Using React JS to Sort an Array Based on a Specific String

Here I am again, this time dealing with reactjs. I have a json object containing two "rows", labeled as Description and ubication. My goal is to filter the array based on the Description field. How can I achieve this? The description is in text format, f ...

Unable to create symbolic link when installing a node module in Docker on Windows leads to failure

I am encountering an issue with my nodejs docker instance running on Windows. I have linked a write-enabled windows directory to the docker instance and I am attempting to install shelljs into my project. However, the installation is failing with the follo ...

In TypeScript, a generic function with an index constraint

Is it possible to define an element that operates in the manner indicated here? function fn<T, U extends keyof T, T[U] extends number>() I am having trouble making the "T[U] extends number" portion function correctly. ...

I attempted to retrieve the id field of a jsonwebtoken following the user's login, but unfortunately, I was unable to access it

While working on the backend of my application, I encountered an issue trying to save the id field from a JSON Web Token (JWT) to an item that I created after a user logs in. Although I am able to log the JWT information successfully, I'm facing diffi ...

What is the process for removing a node module from npmjs?

Is it possible to unpublish my project monetrum-node-client from my personal account on npm and publish it from the company account? I need your assistance with this. This is the error message I received: PS C:\nodejs\prod\monetrum-node-cl ...

Ways to retrieve the property of an object within a view while being sourced from an observable

I am currently working with the following provider code: getWorldCities2() { return this.http.get('../assets/city.list.json') .map(res => res.json()); } Within my TypeScript code, I have implemented the following: ionViewDidLoad() { ...

Retrieve the total number of hours within a designated time frame that falls within a different time frame

Having a difficult time with this, let me present you with a scenario: A waiter at a restaurant earns $15/hour, but between 9:00 PM and 2:30 AM, he gets paid an additional $3/hour. I have the 'start' and 'end' of the shift as Date obje ...

Collapse an array containing objects with nested objects inside

Similar questions can be found here and here, but I am struggling to modify the code provided in the answers to fit my specific needs due to its conciseness. The structure of my array of objects is as follows: [ { id: 1, someProp: &quo ...

The specified 'Promise<Modules>' type argument cannot be assigned to the parameter of type '(params: any) => Promise<Modules>' in the current context

Looking for some help with this helper function that I need to call, it has the following signature: export const fetchPaginated = async <T>( callback: (params: any) => Promise<T>, { page = 1, pageSize, }: { page?: number; page ...

Creating and incorporating a generator function within an interface and class: A step-by-step guide

In vanilla JavaScript, the code would look something like this: class Powers { *[Symbol.iterator]() { for(let i = 0; i < 10; i++) yield { i, pow: Math.pow(i, i) } return null; } } This can then be utilized in the following manner: co ...

Does anyone know how to retrieve the application version or import the package.json file? Can't seem to find the solution on

I need to display the version from the package.json file in my Angular application. To import it, I allowed importing json by adding a few extra lines in tsconfig.json: { "compilerOptions": { "module": "commonjs", ...

The issue with sorting in Angular 8 mat tables persists when dealing with multiple tables

As a newcomer to Angular, I am still learning and have encountered an issue with sorting in the mat table. I have multiple tables on one page, each separated by a mat tab. The problem is that sorting only works on the first table ("crane master list") in t ...

reading an array of objects using typescript

Trying to retrieve an object from an array called pVal. pVal is the array that includes objects. I am attempting to obtain the value of "group" based on the id provided. For instance, if the id is equal to 1, it should display "VKC". Any assistance woul ...

How to access the component instance in Angular through router events

I am currently working on incorporating a title service into my Angular 10 application. My goal is to subscribe to router events, access the activated route's component, check if it has a title() getter, and then use that information to set the page&a ...

In TypeScript, develop a specialized Unwrap<T> utility type

After successfully creating a helper type to unwrap the inner type of an Observable<T>, I began wondering how to make this type completely generic. I wanted it to apply to any type, not just Observable, essentially creating Unwrap<T>. Here is ...

Assign the proxy value in package.json to an environment variable

Is there a way to dynamically set the proxy value in my package.json file using an environment variable at runtime? // package.json { "name": "demo", "proxy": process.env.MY_PROXY_VAL , // <- how? "dependencies": {}, "scripts": {}, } Any sugg ...

Printing req using console.log will allow you to see the data stored in

Upon running a console.log(req);, I discovered that the data from the database is appearing alongside the session data. sessionStore: MySQLStore { . . . options: { host: 'localhost', user: 'root', password: &ap ...