Guide on specifying the index file for a TypeScript npm package

I have a TypeScript package with the main module located in the src directory, named Popover.ts. The main index file is called index.js, and the main field in the package.json points to that file. Here's the content of the main module:

exports.Popover = require('./src/js/Popover');

When I try to include this plugin in another package by installing it using npm, issues arise. Everything works fine in JavaScript:

const Popover = require('popover');

However, when I attempt to import it into a TypeScript file (demo.ts), it doesn't work:

import Popover from 'popover';

In PhpStorm, 'popover' is highlighted with a red line and displays an error message: Can not find module 'popover'. Furthermore, when I build the demo with webpack, there are no errors, but the build file does not contain the contents of Popover.ts.

I'm struggling to understand why this is happening and how to resolve it.

Update: By setting "moduleResolution": "node" in tsconfig.json as suggested by @user254694, I was able to remove the red highlighting in PhpStorm. However, the build then failed with the following TypeScript error generated by Webpack:

Error: TypeScript emitted no output for 
F:\dev\js\plugins\popover\demo\npm\node_modules\popover\src\js\Popover.ts. 
By default, ts-loader will not compile .ts files in node_modules.

To address this, I added the allowTsInNodeModules option to ts-loader:

loader: 'ts-loader',
options: {
   allowTsInNodeModules: true
}

Additionally, I included the following lines in tsconfig.js:

"include": [
    "node_modules/popover/src/**/*",
    "node_modules/popover/index.js",
    "node_modules/popover/typings/**/*"
  ]

Although this resolved the webpack error and allowed successful compilation, the red highlighting reappeared in PhpStorm.

PS: I created declaration types in the typings directory, leading my package.json to look like this:

"main": "index.js",
"types": "typings/index.d.ts",

I am still seeking a solution to make everything function correctly.

Answer №1

Ensure your package includes the index.d.ts file. Additionally, your package.json should have a types field pointing to that file. This will enable importing the package from within node_modules when using typescript.

The index.d.ts file is generated by the TypeScript compiler alongside the index.js file when the --declaration compiler option is enabled. If you plan on publishing your package using npm, ensure this option is added in the tsconfig.json file or via command line.

During webpack demo build, no errors were encountered. However, the resulting build file did not include the contents of Popover.ts.

If you are not actively utilizing the imported Popover module in your typescript file, the compiler may omit it as an optimization strategy. In such cases, Popover.js will not be included in the bundle. If you encounter issues where the compiled javascript does not function properly despite successful compilation with TypeScript, but direct usage of the module in JavaScript works fine - further investigation and details would be needed to address this unusual scenario.

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

Retrieve the data from the mat-checkbox

My goal is to retrieve a value from a mat-checkbox, but the issue is that we only get boolean expression instead of the string value. Here's an example snippet of what I'm looking for: <mat-checkbox formControlName="cb2" <strong&g ...

Utilize Angular 2 to upload and access files directly on the client side

How can I obtain log file(s) from a user so that I can analyze them? Is there a way to create a drop area where the user can upload a file, and then I can read it using JavaScript? I am currently using Angular2 rc5 and have node.js running on the backend, ...

Exploring the Issue with SWR Hook in Next.js using TypeScript

Seeking assistance with the SWR hook as I navigate through some challenges while attempting to use it effectively. This time, the issue appears to be minor. The objective is to set a breakpoint in my API to retrieve data, using axios. The problem arises ...

The image map library functions seamlessly with React but encounters issues when integrated with Next.js

I have been working on a client project that requires the use of an image map. I searched for a suitable library, but struggled to find one that is easy to maintain. However, I came across this particular library that seemed promising. https://github.com/ ...

Preventing data binding in an Angular 2 Kendo grid

Looking for a solution to improve performance on a page with a Kendo grid that contains a high number of rows. Each row has complex logic for showing/hiding elements based on column values, which is causing performance issues when dealing with 100 or mor ...

Having trouble navigating the path in the VS Code terminal while using npm

I have a project that I'm working on located at: Documents\CoursReact\carsApp\cars. When I try to run it using the following commands: cd cars npm start I am faced with multiple issues such as: npm ERR! code ENOENT npm ERR! syscall o ...

Can metadata be attached to data models in Angular for annotation purposes?

Looking to add some metadata annotations to a simple data model export class Certification { title: string; certificationType?: CertificationType; validTo?: number; description?: string; externalIdentifier: Guid; constructor() { ...

Is it possible to invoke JavaScript code from TypeScript?

I'm struggling with calling a JavaScript file from TypeScript. After resolving one import issue and adjusting the base function for tsc recognition, I'm now stuck on recognizing a declared function prototype in the JavaScript file. Although I ha ...

Incorporate generic types into Promise.props(...) using Typescript

I am currently working on developing a custom typed Promise.props(...) utility function that dynamically assigns correct types based on the input object. static async props<T extends {[key: string]: Promise<S>|S}, S, U extends { [key in keyof T]: ...

Creating dynamic types in TypeScript through existing types

Consider the following object: class Product { constructor( public metadata: Metadata, public topic: Topic, public title = 'empty' ) {} ... } I am looking to define an interface: interface State<T> { } This interface s ...

There seems to be an issue with the NPM command configuration

I made changes to npm config set <key> <value> and now I'm experiencing issues when trying to run commands related to npm config. The error message I am receiving is: Error: Failed parsing JSON config key Is there a way to reset my npm ...

npm encountered an error trying to locate the Python executable "python3" within the PATH directories

When I run npm install in the root directory of my project, I encounter the following errors on Ubuntu22. $ node -v v19.2.0 $ npm -v 8.19.3 package.json { "private": true, "scripts": { "dev": "npm run dev ...

Unable to associate with 'ngIF' as it is not recognized as a valid property of 'ion-item'

I am facing a challenge in implementing *ngIF within the code of my Ionic4 project. I have come across some solutions, but none seem to be compatible with ionic 4 and angular 7. I attempted to import the imports: [CommonModule] part, but unfortunately, it ...

The property xyz is not found in the type 'IntrinsicAttributes & interface abc'

I have an array of objects structured like this: const data = { "Large_Plates": [ { "name": "Cauliower/ Shanghai Fried rice with stir fry vegetables", "id": "1", "price_Veg&quo ...

Automatic type inference for TypeScript getters

It appears that Typescript infers field types based solely on the private variable of a field, rather than taking into account the getter's return type union (1) or inferring from the getter itself (2): test('field type inference', () =& ...

Converting JSON data into an array of a particular type in Angular

My current challenge involves converting JSON data into an array of Recipe objects. Here is the response retrieved from the API: { "criteria": { "requirePictures": true, "q": null, "allowedIngredient": null, "excluded ...

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 ...

Challenges in Power BI Custom Visual Development: Trouble setting height for div elements

Currently, I am working on creating a custom visual for Power BI that includes a leaflet map within a div element. However, the issue arises when I fail to set a specific height for the map, resulting in an empty visual. I have managed to set a fixed heigh ...

Having difficulty with sending just the selected value using TypeScript

I've encountered an issue with sending the value of a select input to my database while working with Vue, Quasar, and TypeScript. Within a modal, I have name and age inputs along with a select that chooses a category. However, when attempting to send ...

The error message indicates that the property `v.context.$implicit` is not callable

I am a beginner with Typescript and it has only been 3 days. I am trying to access data from Firebase and display it in a list. However, I keep encountering an error when trying to navigate to another page using (Click) ="item ()". Can someone point out wh ...